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): creating drafts & sending actual attachments in email compose (#995)

dev-rbed676e4437d3
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index ded12d434d..24e0e18877 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -356,17 +356,19 @@ export function BaseInput(props: {
{ type: 'local' }
>[];
- const uploaded = await uploadAttachmentMutation.mutateAsync({
- draftID: draftResponse,
- attachments: attachments.map((a) => a.file),
- });
+ if (attachments.length) {
+ 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
- );
+ // Assign the attachment ids to attachments for later use
+ for (const attachment of uploaded.attachments) {
+ form().attachments.assignAttachmentID(
+ attachment.file,
+ attachment.attachmentID
+ );
+ }
}
setSavedDraftId(draftResponse);
@@ -895,6 +897,7 @@ export function BaseInput(props: {
value={form().subject()}
onInput={(e) => {
form().setSubject(e.currentTarget.value);
+ scheduleDraftSave();
}}
placeholder="Subject"
/>
diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsx
index 4c4bc87ee0..fc9c9175cc 100644
--- a/js/app/packages/block-email/component/Compose.tsx
+++ b/js/app/packages/block-email/component/Compose.tsx
@@ -34,8 +34,31 @@ import {
Switch,
} from 'solid-js';
import { beveledCorners } from '../../block-theme/signals/themeSignals';
-import { ComposeEmailInput, type ComposeInputData } from './ComposeEmailInput';
-import { createEmailFormState } from '@block-email/component/createEmailFormState';
+import { ComposeEmailInput } from './ComposeEmailInput';
+import {
+ createEmailFormState,
+ type DraftFormAttachment,
+} from '@block-email/component/createEmailFormState';
+import { logger } from '@observability/logger';
+import { debounce } from '@solid-primitives/scheduled';
+import type { LexicalEditor } from 'lexical';
+import {
+ $appendWatermarkNodeToLast,
+ $removeAllWatermarkNodes,
+} from '@lexical-core';
+import { prepareEmailBody } from '@block-email/util/prepareEmailBody';
+import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';
+import {
+ deleteEmailDraft,
+ saveEmailDraft,
+} from '@block-email/signal/emailDraft';
+import {
+ useRemoveDraftAttachmentMutation,
+ useUploadDraftAttachmentsMutation,
+} from '@queries/email/attachment';
+import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
+
+const DRAFT_DEBOUNCE_MS = 1000;
type EmailComposeErrors =
| 'no_recipient'
@@ -103,6 +126,140 @@ export function EmailCompose() {
const form = createEmailFormState();
+ const [editor, setEditor] = createSignal<LexicalEditor | undefined>();
+
+ const [content, setContent] = createSignal('');
+ const [currentDraftID, setCurrentDraftID] = createSignal<
+ string | undefined
+ >();
+
+ const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();
+
+ function collectDraft() {
+ $removeAllWatermarkNodes(editor());
+ const prepared = prepareEmailBody(editor());
+ if (!prepared) {
+ logger.error(
+ new Error('Unable to prepare email body for draft collection.')
+ );
+ return null;
+ }
+ // 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
+ return {
+ bcc: form.recipients().bcc.map(convertEmailRecipientToContactInfo),
+ body_html: prepared.bodyHtml,
+ cc: form.recipients().cc.map(convertEmailRecipientToContactInfo),
+ subject: form.subject(),
+ to: form.recipients().to.map(convertEmailRecipientToContactInfo),
+ };
+ }
+
+ async function executeSaveDraft() {
+ if (sendMutation.isPending) {
+ return;
+ }
+ const draftToSave = collectDraft();
+ if (!draftToSave) {
+ const draftID = currentDraftID();
+ if (draftID) {
+ await deleteEmailDraft(draftID);
+ }
+ setCurrentDraftID(undefined);
+ return;
+ }
+
+ const linkID = link()?.id;
+ if (!linkID || hasLinkError()) {
+ logger.error(
+ new Error('Failed to save email draft: could not load email links')
+ );
+ return false;
+ }
+
+ const draftResponse = await saveEmailDraft({
+ ...draftToSave,
+ link_id: linkID,
+ });
+
+ 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' }
+ >[];
+
+ if (attachments.length) {
+ 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
+ );
+ }
+ }
+
+ setCurrentDraftID(draftResponse);
+ }
+ }
+
+ const scheduleDraftSave = debounce(() => {
+ void executeSaveDraft();
+ }, DRAFT_DEBOUNCE_MS);
+
+ const onAddAttachments = (attachments: DraftFormAttachment[]) => {
+ for (const attachment of attachments) {
+ form.attachments.add(attachment);
+ }
+ scheduleDraftSave();
+ };
+
+ const removeAttachmentMutation = useRemoveDraftAttachmentMutation();
+
+ const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ if (attachment.type === 'local') {
+ form.attachments.removeByFile(attachment.file);
+ } else {
+ form.attachments.removeByID(attachment.attachmentID);
+ }
+
+ const savedDraftID = currentDraftID();
+
+ if (!savedDraftID || !attachment.attachmentID) return;
+
+ removeAttachmentMutation.mutate({
+ draftID: savedDraftID,
+ attachmentID: attachment.attachmentID,
+ });
+ };
+
+ // We are consuming the first change, because it is the initial value
+ let firstChangeConsumed = false;
+ const onContentChange = (content: string) => {
+ setContent(content);
+ if (!firstChangeConsumed) {
+ firstChangeConsumed = true;
+ return;
+ }
+ scheduleDraftSave();
+ };
+
const [showCc, setShowCc] = createSignal(false);
const [showBcc, setShowBcc] = createSignal(false);
@@ -248,9 +405,30 @@ export function EmailCompose() {
},
});
- const onSubmit = (data: ComposeInputData) => {
+ const onSubmit = () => {
setValidationError(null);
+ const currentEditor = editor();
+
+ // We handle cleaning up the signature after we've sent the request because
+ // otherwise the `bodyMacro` signal would update after the clean up call and
+ // not contain the signature in the request data
+ const cleanupWatermark = $appendWatermarkNodeToLast(
+ currentEditor,
+ !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
+ );
+
+ const prepared = prepareEmailBody(currentEditor, undefined);
+ if (!prepared) return;
+
+ const bodyMacro = content();
+
+ const data = {
+ text: prepared.bodyText,
+ html: prepared.bodyHtml,
+ raw: bodyMacro,
+ };
+
const currentLink = link();
const recipients = form.recipients();
@@ -265,7 +443,7 @@ export function EmailCompose() {
return;
}
- if (!data.body.raw.trim()) {
+ if (!data.raw.trim()) {
setValidationError(
new EmailComposeError('no_message', 'Please enter a message')
);
@@ -299,12 +477,14 @@ export function EmailCompose() {
? convertToContactInfoArray(recipients.bcc)
: [],
subject: form.subject(),
- body_text: data.body.text,
- body_html: data.body.html,
- body_macro: data.body.raw,
- attachments: [],
+ body_text: data.text,
+ body_html: data.html,
+ body_macro: data.raw,
+ db_id: currentDraftID(),
},
});
+
+ cleanupWatermark();
};
const withValidationError = (type: EmailComposeErrors) => {
@@ -507,6 +687,7 @@ export function EmailCompose() {
class="w-full text-base resize-none placeholder:text-ink-placeholder p-1 ml-1"
onInput={(e) => {
form.setSubject(e.currentTarget.value);
+ scheduleDraftSave();
}}
disabled={hasLinkError()}
/>
@@ -530,10 +711,15 @@ export function EmailCompose() {
}}
>
<ComposeEmailInput
+ captureEditor={setEditor}
inputRef={registerRef('messageInput')}
+ onContentChange={onContentChange}
+ onAddAttachments={onAddAttachments}
+ onRemoveAttachment={handleRemoveAttachment}
+ attachments={form.attachments.list()}
onSubmit={onSubmit}
isSubmitting={sendMutation.isPending}
- disabled={hasLinkError()}
+ disabled={hasLinkError() || sendMutation.isPending}
/>
<Show when={withValidationError('no_message')}>
{(err) => (
diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsx
index de616432ea..8a6f533b35 100644
--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx
+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx
@@ -1,22 +1,15 @@
import { useSplitPanel } from '@app/component/split-layout/layoutUtils';
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
-import {
- MACRO_EMAIL_SIGNATURE,
- MAX_ATTACHMENTS_BYTES_SIZE,
-} from '@block-email/constants';
+import { MAX_ATTACHMENTS_BYTES_SIZE } from '@block-email/constants';
import { useHasPaidAccess } from '@core/auth';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
-import {
- createFilesReadyHandler,
- getDragDropPosition,
-} from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
+import { createFilesReadyHandler } from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { handleFileFolderDrop } from '@core/util/upload';
import TextAa from '@icon/regular/text-aa.svg';
-import { $appendWatermarkNodeToLast } from '@lexical-core';
import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import ArrowFatLineUp from '@phosphor-icons/core/fill/arrow-fat-line-up-fill.svg?component-solid';
import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
@@ -32,48 +25,29 @@ import {
type LexicalEditor,
type TextFormatType,
} from 'lexical';
-import { createSignal, onMount, Show } from 'solid-js';
+import { createSignal, For, Match, onMount, Show, Switch } from 'solid-js';
import { type FocusableElement, tabbable } from 'tabbable';
import { makeAttachmentPublic } from '../util/makeAttachmentPublic';
-import { prepareEmailBody } from '../util/prepareEmailBody';
import { Button } from '@ui/components/Button';
import { fileSelector } from '@core/directive/fileSelector';
import { toast } from '@core/component/Toast/Toast';
import { plural } from '@core/util/string';
+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';
+import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';
false && fileFolderDrop;
-export type ComposeInputData = {
- body: {
- text: string;
- html: string;
- raw: string;
- };
-};
-
-export type ComposeAttachment =
- | {
- type: 'local';
- file: File;
- attachmentID?: string;
- }
- | {
- type: 'remote';
- url: string;
- fileName: string;
- contentType: string;
- attachmentID: string;
- fileSize: number;
- };
-
type ComposeEmailInputProps = {
inputRef?: (el: HTMLDivElement) => void;
- onSubmit: (data: ComposeInputData) => void;
+ captureEditor?: (editor: LexicalEditor) => void;
+ onSubmit: () => void;
disabled?: boolean;
loading?: boolean;
isSubmitting?: boolean;
- attachments?: ComposeAttachment[];
- onAddAttachments?: (attachments: ComposeAttachment[]) => void;
+ attachments?: DraftFormAttachment[];
+ onAddAttachments?: (attachments: DraftFormAttachment[]) => void;
+ onRemoveAttachment?: (attachment: DraftFormAttachment) => void;
+ onContentChange?: (content: string) => void;
};
export function ComposeEmailInput(props: ComposeEmailInputProps) {
@@ -85,8 +59,6 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(false);
- const [content, setContent] = createSignal('');
-
const panel = useSplitPanel();
const focusSibling = (direction: 'next' | 'prev') => {
@@ -120,31 +92,8 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
HTMLElement | undefined
>();
- async function handleSend() {
- const currentEditor = editor();
-
- // We handle cleaning up the signature after we've sent the request because
- // otherwise the `bodyMacro` signal would update after the clean up call and
- // not contain the signature in the request data
- const cleanupWatermark = $appendWatermarkNodeToLast(
- currentEditor,
- !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
- );
-
- const prepared = prepareEmailBody(currentEditor, undefined);
- if (!prepared) return;
-
- const bodyMacro = content();
-
- props.onSubmit({
- body: {
- text: prepared.bodyText,
- html: prepared.bodyHtml,
- raw: bodyMacro,
- },
- });
-
- cleanupWatermark();
+ function handleSend() {
+ props.onSubmit();
}
onMount(() => {
@@ -155,16 +104,11 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
const onAddFilesAndDirs = (
files: FileSystemFileEntry[],
- directories: FileSystemDirectoryEntry[],
- dropEvent?: DragEvent
+ directories: FileSystemDirectoryEntry[]
) => {
const editor_ = editor();
if (!editor_) return;
- const getPositionCallback = dropEvent
- ? () => getDragDropPosition(editor_, dropEvent, true)
- : undefined;
-
handleFileFolderDrop(
files,
directories,
@@ -172,7 +116,7 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
editor_,
undefined,
undefined,
- getPositionCallback,
+ undefined,
(uploadedItemIds) => {
uploadedItemIds.forEach((itemId) => {
makeAttachmentPublic(itemId);
@@ -230,6 +174,11 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
);
};
+ const captureEditor = (editor: LexicalEditor) => {
+ setEditor(editor);
+ props.captureEditor?.(editor);
+ };
+
return (
<div
ref={setComposeContainerRef}
@@ -258,7 +207,11 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
use:fileFolderDrop={{
onDragStart: () => setIsDragging(true),
onDragEnd: () => setIsDragging(false),
- onDrop: onAddFilesAndDirs,
+ onDrop: (files, dirs) => {
+ handleFileFolderDrop(files, dirs, (u) =>
+ handleAddAttachments(u.map((f) => f.file))
+ );
+ },
}}
>
<div class={`${!isDragging() && 'hidden'} absolute inset-0`}>
@@ -266,12 +219,12 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
</div>
<MarkdownTextarea
domRef={props.inputRef}
- captureEditor={setEditor}
+ captureEditor={captureEditor}
class="text-sm break-words text-ink"
editable={() => !props.disabled}
placeholder="Use `@` to reference files"
watermark={!hasPaidAccess() ? <MacroSignatureButton /> : undefined}
- onChange={setContent}
+ onChange={props.onContentChange}
onFocusLeaveStart={(e) => {
e.preventDefault();
focusSibling('prev');
@@ -284,6 +237,43 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
onPasteFilesAndDirs={onAddFilesAndDirs}
/>
</div>
+ <div class="flex flex-wrap items-center gap-2">
+ <For each={props.attachments}>
+ {(attachment) => {
+ const handleRemoveAttachment = () => {
+ props.onRemoveAttachment?.(attachment);
+ };
+ return (
+ <Switch>
+ <Match when={attachment.type === 'local' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().file.name,
+ mimeType: attachment().file.type,
+ }}
+ removable
+ onRemove={handleRemoveAttachment}
+ />
+ )}
+ </Match>
+ <Match when={attachment.type === 'remote' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().fileName,
+ mimeType: attachment().contentType,
+ }}
+ removable
+ onRemove={handleRemoveAttachment}
+ />
+ )}
+ </Match>
+ </Switch>
+ );
+ }}
+ </For>
+ </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">