Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(email): refactor email form states (#993)
dev-rbee2f77e7cb3f
diff --git a/js/app/packages/app/component/QuickCreateMenu.tsx b/js/app/packages/app/component/QuickCreateMenu.tsxindex 872852dc31..68fca6f0c6 100644--- a/js/app/packages/app/component/QuickCreateMenu.tsx+++ b/js/app/packages/app/component/QuickCreateMenu.tsx@@ -643,7 +643,7 @@ export function QuickCreateMenuInner(props: QuickCreateMenuProps) {<div class="flex w-full focus-within:bracket"><RecipientSelector<'user' | 'contact'>options={usersAndContacts}- selectedOptions={selectedEmailOptions}+ selectedOptions={selectedEmailOptions()}setSelectedOptions={setSelectedEmailOptions}placeholder="Add recipients by email"triedToSubmit={triedToSubmitEmail}@@ -654,7 +654,7 @@ export function QuickCreateMenuInner(props: QuickCreateMenuProps) {<div class="flex w-full focus-within:bracket"><RecipientSelector<'user' | 'contact' | 'channel'>options={destinationOptions}- selectedOptions={selectedOptions}+ selectedOptions={selectedOptions()}setSelectedOptions={setSelectedOptions}placeholder="Add by email or channel"triedToSubmit={triedToSubmit}diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex b387d77d1c..18124c7049 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -1653,7 +1653,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {<span class="font-medium text-xs">From</span><RecipientSelector<'user' | 'contact'>options={emailRecipientOptions}- selectedOptions={fromFilterUsers}+ selectedOptions={fromFilterUsers()}setSelectedOptions={setFromFilterUsers}placeholder="Filter by user..."includeSelfdiff --git a/js/app/packages/block-channel/component/Compose.tsx b/js/app/packages/block-channel/component/Compose.tsxindex 31134c81a1..2be0212108 100644--- a/js/app/packages/block-channel/component/Compose.tsx+++ b/js/app/packages/block-channel/component/Compose.tsx@@ -163,7 +163,7 @@ export function ChannelCompose() {/><RecipientSelector<'user' | 'contact'>options={destinationOptions}- selectedOptions={selectedRecipients}+ selectedOptions={selectedRecipients()}setSelectedOptions={setSelectedRecipients}placeholder="To: Macro users or email addresses"triedToSubmit={triedToSubmit}diff --git a/js/app/packages/block-channel/component/ParticipantManager.tsx b/js/app/packages/block-channel/component/ParticipantManager.tsxindex 1e0502b1b5..21df44d1e2 100644--- a/js/app/packages/block-channel/component/ParticipantManager.tsx+++ b/js/app/packages/block-channel/component/ParticipantManager.tsx@@ -106,7 +106,7 @@ export function ParticipantManager(props: { participantCount: number }) {<div class="flex flex-row justify-between gap-2 min-h-[40px] text-ink-muted border-b border-edge-muted/50 p-2 items-center"><RecipientSelector<'user'>setSelectedOptions={setUsersToInvite}- selectedOptions={usersToInvite}+ selectedOptions={usersToInvite()}placeholder={'Search'}options={options}hideBorderdiff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex 380fd28361..ded12d434d 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -1,7 +1,10 @@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';+import {+ MACRO_EMAIL_SIGNATURE,+ MAX_ATTACHMENTS_BYTES_SIZE,+} from '@block-email/constants';import { useHasPaidAccess } from '@core/auth';import { useBlockId } from '@core/block';import { FileDropOverlay } from '@core/component/FileDropOverlay';@@ -103,8 +106,6 @@ 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) {case 'user':@@ -157,7 +158,7 @@ export function BaseInput(props: {}) {const ctx = useEmailContext();const form = createMemo(() =>- getOrInitEmailFormContext(props.replyingTo().db_id!)()+ getOrInitEmailFormContext(props.replyingTo().db_id!));const blockId = useBlockId();const emailLinksQuery = useEmailLinksQuery();@@ -275,13 +276,13 @@ export function BaseInput(props: {}// We attach the drafts entirely using bodyHTML (because this is how the appended reply parsing works) so we are not including bodyMacro or bodyTextreturn {- bcc: form().recipients.bcc.map(convertEmailRecipientToContactInfo),+ bcc: form().recipients().bcc.map(convertEmailRecipientToContactInfo),body_html: prepared.bodyHtml,- cc: form().recipients.cc.map(convertEmailRecipientToContactInfo),+ cc: form().recipients().cc.map(convertEmailRecipientToContactInfo),provider_id: props.draft?.provider_id,replying_to_id: props.replyingTo()?.db_id,subject: form().subject(),- to: form().recipients.to.map(convertEmailRecipientToContactInfo),+ to: form().recipients().to.map(convertEmailRecipientToContactInfo),};}@@ -400,8 +401,8 @@ export function BaseInput(props: {!combobox?.contains(e.target as Node)) {setShowExpandedRecipients(false);- setShowCc(form().recipients.cc.length > 0);- setShowBcc(form().recipients.bcc.length > 0);+ setShowCc(form().recipients().cc.length > 0);+ setShowBcc(form().recipients().bcc.length > 0);}}};@@ -424,9 +425,9 @@ export function BaseInput(props: {const sendEmail = async (markDone = false) => {if (sendMutation.isPending || uploadAttachmentMutation.isPending) return;- const to = form().recipients.to.map(convertEmailRecipientToContactInfo);- const cc = form().recipients.cc.map(convertEmailRecipientToContactInfo);- const bcc = form().recipients.bcc.map(convertEmailRecipientToContactInfo);+ const to = form().recipients().to.map(convertEmailRecipientToContactInfo);+ const cc = form().recipients().cc.map(convertEmailRecipientToContactInfo);+ const bcc = form().recipients().bcc.map(convertEmailRecipientToContactInfo);if ((to?.length ?? 0) + (cc?.length ?? 0) + (bcc?.length ?? 0) === 0) {toast.failure('Email failed to send. No recipients provided');@@ -542,17 +543,21 @@ export function BaseInput(props: {const mentionEmail = mention.mentions[0].split('|')[1];// Check if user already in To or CC- const isInTo = form().recipients.to.some((recipient: EmailRecipient) => {- const email = recipient.data.email;- if (!email) return false;- return email === mentionEmail;- });+ const isInTo = form()+ .recipients()+ .to.some((recipient: EmailRecipient) => {+ const email = recipient.data.email;+ if (!email) return false;+ return email === mentionEmail;+ });- const isInCc = form().recipients.cc.some((recipient: EmailRecipient) => {- const email = recipient.data.email;- if (!email) return false;- return email === mentionEmail;- });+ const isInCc = form()+ .recipients()+ .cc.some((recipient: EmailRecipient) => {+ const email = recipient.data.email;+ if (!email) return false;+ return email === mentionEmail;+ });// If not already in To or CC, add user to CCif (!isInTo && !isInCc) {@@ -565,10 +570,7 @@ export function BaseInput(props: {if (userOption) {// Add to CC recipients- form().setRecipients('cc', (prev: EmailRecipient[]) => [- ...(prev ?? []),- userOption,- ]);+ form().setRecipients('cc', [...form().recipients().cc, userOption]);toast.success(`${mentionEmail} added to CC`);}}@@ -769,9 +771,9 @@ export function BaseInput(props: {><Showwhen={- form().recipients.to.length +- form().recipients.cc.length +- form().recipients.bcc.length >+ form().recipients().to.length ++ form().recipients().cc.length ++ form().recipients().bcc.length >0}fallback={@@ -780,23 +782,24 @@ export function BaseInput(props: {><Showwhen={- form().recipients.to.length + form().recipients.cc.length >+ form().recipients().to.length ++ form().recipients().cc.length >0}><span>to </span></Show><RecipientList- recipients={form().recipients.to}- showTrailingComma={form().recipients.cc.length > 0}+ recipients={form().recipients().to}+ showTrailingComma={form().recipients().cc.length > 0}/><RecipientList- recipients={form().recipients.cc}+ recipients={form().recipients().cc}showTrailingComma={false}/>- <Show when={form().recipients.bcc.length > 0}>, bcc: </Show>+ <Show when={form().recipients().bcc.length > 0}>, bcc: </Show><RecipientList- recipients={form().recipients.bcc}+ recipients={form().recipients().bcc}showTrailingComma={false}/></Show>@@ -818,20 +821,20 @@ export function BaseInput(props: {<RecipientSelector<EmailRecipient['kind']>inputRef={setToRef}options={ctx.recipientOptions}- selectedOptions={() => form().recipients.to}+ selectedOptions={form().recipients().to}setSelectedOptions={(v) => form().setRecipients('to', v)}triggerMode="input"hideBorder/></div>{/* Expanded CC */}- <Show when={showCc() || form().recipients.cc.length > 0}>+ <Show when={showCc() || form().recipients().cc.length > 0}><div class="flex flex-row items-start"><div class="text-sm text-ink-muted min-w-8">cc</div><RecipientSelector<EmailRecipient['kind']>inputRef={setCcRef}options={ctx.recipientOptions}- selectedOptions={() => form().recipients.cc}+ selectedOptions={form().recipients().cc}setSelectedOptions={(v) => form().setRecipients('cc', v)}triggerMode="input"hideBorder@@ -839,13 +842,13 @@ export function BaseInput(props: {</div></Show>{/* Expanded BCC */}- <Show when={showBcc() || form().recipients.bcc.length > 0}>+ <Show when={showBcc() || form().recipients().bcc.length > 0}><div class="flex flex-row items-start"><div class="text-sm text-ink-muted min-w-8">bcc</div><RecipientSelector<EmailRecipient['kind']>inputRef={setBccRef}options={ctx.recipientOptions}- selectedOptions={() => form().recipients.bcc}+ selectedOptions={form().recipients().bcc}setSelectedOptions={(v) => form().setRecipients('bcc', v)}triggerMode="input"hideBorderdiff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex 843c9996ed..4c4bc87ee0 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -35,6 +35,7 @@ import {} from 'solid-js';import { beveledCorners } from '../../block-theme/signals/themeSignals';import { ComposeEmailInput, type ComposeInputData } from './ComposeEmailInput';+import { createEmailFormState } from '@block-email/component/createEmailFormState';type EmailComposeErrors =| 'no_recipient'@@ -62,8 +63,6 @@ export function EmailCompose() {const hasPaidAccess = useHasPaidAccess();const { showPaywall } = usePaywallState();- const [subject, setSubject] = createSignal<string>('');-const emailLinksQuery = useEmailLinksQuery();const [refs, setRefs] = createSignal<EmailComposeElementRefs>({@@ -101,15 +100,8 @@ export function EmailCompose() {});const { users: destinationOptions } = useCombinedRecipients();- const [selectedRecipients, setSelectedRecipients] = createSignal<- WithCustomUserInput<'user' | 'contact'>[]- >([]);- const [ccRecipients, setCcRecipients] = createSignal<- WithCustomUserInput<'user' | 'contact'>[]- >([]);- const [bccRecipients, setBccRecipients] = createSignal<- WithCustomUserInput<'user' | 'contact'>[]- >([]);++ const form = createEmailFormState();const [showCc, setShowCc] = createSignal(false);const [showBcc, setShowBcc] = createSignal(false);@@ -201,37 +193,39 @@ export function EmailCompose() {shouldReturnFocusOnClose: false,});- const [triedToSubmit, _setTriedToSubmit] = createSignal(false);-const { connect: connectEmail } = useEmailLinks();const previewName = createMemo(() => {- const recipients = selectedRecipients();+ const recipients = form.recipients().to;if (recipients.length === 0) {return 'Draft email';- } else if (recipients.length === 1) {- const recipientName =- recipients[0].kind === 'user'- ? useDisplayName(tryMacroId(recipients[0].data.id))[0]()- : recipients[0].data.email;- return recipientName ? `Email to ${recipientName}` : 'Draft email';- } else {- const names = recipients- .slice(0, 2)- .map((r) => {- if (r.kind === 'user') {- return useDisplayName(tryMacroId(r.data.id))[0]();- }- return r.data.email || 'Unknown';- })- .filter(Boolean);-- if (recipients.length > 2) {- return `Email to ${names.join(', ')}, and others`;- } else {- return `Email to ${names.join(' and ')}`;+ }++ if (recipients.length === 1) {+ let recipientName = recipients[0].data.email;++ if (recipients[0].kind === 'user') {+ recipientName = useDisplayName(tryMacroId(recipients[0].data.id))[0]();}++ return recipientName ? `Email to ${recipientName}` : 'Draft email';+ }++ const names = recipients+ .slice(0, 2)+ .map((r) => {+ if (r.kind === 'user') {+ return useDisplayName(tryMacroId(r.data.id))[0]();+ }+ return r.data.email || 'Unknown';+ })+ .filter(Boolean);++ if (recipients.length > 2) {+ return `Email to ${names.join(', ')}, and others`;}++ return `Email to ${names.join(' and ')}`;});const { replaceSplit } = useSplitLayout();@@ -259,7 +253,9 @@ export function EmailCompose() {const currentLink = link();- if (!selectedRecipients().length) {+ const recipients = form.recipients();++ if (!recipients.to.length) {setValidationError(new EmailComposeError('no_recipient',@@ -276,7 +272,7 @@ export function EmailCompose() {return;}- if (!subject()?.trim()) {+ if (!form.subject()?.trim()) {setValidationError(new EmailComposeError('no_subject', 'Please enter a subject'));@@ -293,16 +289,16 @@ export function EmailCompose() {sendMutation.mutate({message: {link_id: currentLink.id,- to: convertToContactInfoArray(selectedRecipients()),+ to: convertToContactInfoArray(recipients.to),cc:- ccRecipients().length > 0- ? convertToContactInfoArray(ccRecipients())+ recipients.cc.length > 0+ ? convertToContactInfoArray(recipients.cc): [],bcc:- bccRecipients().length > 0- ? convertToContactInfoArray(bccRecipients())+ recipients.bcc.length > 0+ ? convertToContactInfoArray(recipients.bcc): [],- subject: subject(),+ subject: form.subject(),body_text: data.body.text,body_html: data.body.html,body_macro: data.body.raw,@@ -321,7 +317,7 @@ export function EmailCompose() {<><SplitHeaderLeft><StaticSplitLabel- label={subject() || previewName()}+ label={form.subject() || previewName()}iconType="email"badges={[<SplitHeaderBadge text="draft" tooltip="This is a Draft Email" />,@@ -433,10 +429,11 @@ export function EmailCompose() {<RecipientSelector<'user' | 'contact'>inputRef={registerRef('directRecipientsSelector')}options={destinationOptions}- selectedOptions={selectedRecipients}- setSelectedOptions={setSelectedRecipients}+ selectedOptions={form.recipients().to}+ setSelectedOptions={(next) =>+ form.setRecipients('to', next)+ }placeholder="Macro users or email addresses"- triedToSubmit={triedToSubmit}focusOnMount={!hasLinkError()}hideBordernoBrackets@@ -461,10 +458,11 @@ export function EmailCompose() {<RecipientSelector<'user' | 'contact'>inputRef={registerRef('ccRecipientsSelector')}options={destinationOptions}- selectedOptions={ccRecipients}- setSelectedOptions={setCcRecipients}+ selectedOptions={form.recipients().cc}+ setSelectedOptions={(next) =>+ form.setRecipients('cc', next)+ }placeholder="Macro users or email addresses"- triedToSubmit={triedToSubmit}hideBordernoBracketsdisabled={hasLinkError()}@@ -482,10 +480,11 @@ export function EmailCompose() {<RecipientSelector<'user' | 'contact'>inputRef={registerRef('bccRecipientsSelector')}options={destinationOptions}- selectedOptions={bccRecipients}- setSelectedOptions={setBccRecipients}+ selectedOptions={form.recipients().bcc}+ setSelectedOptions={(next) =>+ form.setRecipients('bcc', next)+ }placeholder="Macro users or email addresses"- triedToSubmit={triedToSubmit}hideBordernoBracketsdisabled={hasLinkError()}@@ -503,11 +502,11 @@ export function EmailCompose() {<inputref={registerRef('subjectInput')}type="text"- value={subject()}+ value={form.subject()}placeholder="Subject"class="w-full text-base resize-none placeholder:text-ink-placeholder p-1 ml-1"onInput={(e) => {- setSubject(e.currentTarget.value);+ form.setSubject(e.currentTarget.value);}}disabled={hasLinkError()}/>diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsxindex 1291094d76..de616432ea 100644--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx@@ -1,10 +1,12 @@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 } from '@block-email/constants';+import {+ MACRO_EMAIL_SIGNATURE,+ MAX_ATTACHMENTS_BYTES_SIZE,+} 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 {@@ -14,17 +16,11 @@ 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,-} from '@lexical-core';+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';import { useUserId } from '@service-gql/client';-import type { FileType } from '@service-storage/generated/schemas/fileType';-import type { Item } from '@service-storage/generated/schemas/item';import { defaultSelectionData } from 'core/component/LexicalMarkdown/plugins';import {NODE_TRANSFORM,@@ -39,11 +35,11 @@ import {import { createSignal, onMount, Show } from 'solid-js';import { type FocusableElement, tabbable } from 'tabbable';import { makeAttachmentPublic } from '../util/makeAttachmentPublic';-import {- appendItemsAsMacroMentions,- prepareEmailBody,-} from '../util/prepareEmailBody';-import { AttachMenu } from './AttachMenu';+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';false && fileFolderDrop;@@ -55,11 +51,29 @@ export type ComposeInputData = {};};+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;disabled?: boolean;+ loading?: boolean;isSubmitting?: boolean;+ attachments?: ComposeAttachment[];+ onAddAttachments?: (attachments: ComposeAttachment[]) => void;};export function ComposeEmailInput(props: ComposeEmailInputProps) {@@ -68,7 +82,6 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {const [editor, setEditor] = createSignal<LexicalEditor>();const [isDragging, setIsDragging] = createSignal<boolean>();- const [isPendingUpload, setIsPendingUpload] = createSignal<boolean>(false);const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(false);@@ -100,26 +113,6 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {let bodyDiv!: HTMLDivElement;let attachButtonRef!: HTMLDivElement;- 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);- });- }-- function onAttachDocuments(items: DocumentMentionInfo[]) {- appendItemsAsMacroMentions(editor(), items);- items.forEach((item) => {- makeAttachmentPublic(item.documentId);- });- }-// Set up hotkey scope for the compose message componentconst [attachComposeHotkeys, composeHotkeyScope] =useHotkeyDOMScope('compose-message');@@ -203,6 +196,40 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {displayPriority: 10,});+ const handleAddAttachments = (files: File[]) => {+ const currentAttachments = props.attachments ?? [];++ 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;+ }++ props.onAddAttachments?.(+ files.map((file) => ({+ type: 'local',+ file,+ }))+ );+ };+return (<divref={setComposeContainerRef}@@ -257,35 +284,23 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {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}>- <AttachMenu- trigger={- <DeprecatedIconButton- theme="base"- icon={PaperclipIcon}- tooltip={{ label: 'Attach' }}- disabled={props.disabled}- />+ <Button+ ref={(el) =>+ fileSelector(el, () => ({+ multiple: true,+ onSelect: handleAddAttachments,+ }))}- onAttach={onAttach}- onAttachDocuments={onAttachDocuments}- setIsPending={setIsPendingUpload}- />+ tooltip="Attach"+ class="aspect-square p-1"+ disabled={props.disabled}+ >+ <PaperclipIcon class="h-5" />+ </Button></div><DeprecatedIconButtontheme="base"@@ -298,14 +313,14 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {</div><buttontype="button"- disabled={isPendingUpload() || props.isSubmitting || props.disabled}+ disabled={props.loading || props.isSubmitting || props.disabled}onClick={() => {handleSend();}}class="text-ink-muted focus:scale-110 hover:scale-110 transition ease-in-out delay-150 flex gap-2 justify-center items-center hover:bg-hover py-1 px-2 text-sm"><Show- when={!isPendingUpload() && !props.isSubmitting}+ when={!props.loading && !props.isSubmitting}fallback={<Spinner class="w-5 h-5 animate-spin cursor-disabled" />}><span class="font-medium font-mono uppercase">Send</span>diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsxindex ad60558fa3..4e2c09acf3 100644--- a/js/app/packages/block-email/component/Email.tsx+++ b/js/app/packages/block-email/component/Email.tsx@@ -394,7 +394,14 @@ function EmailContent(props: EmailViewProps) {});return (- <EmailFormContextProvider>+ <EmailFormContextProvider+ formOptions={{+ getMessageByID: (id) =>+ context.messages.list().find((m) => m.db_id === id),+ getDraftForMessageReply: context.drafts.getDraftForMessage,+ onRecipientsChange: context.onRecipientsChange,+ }}+ ><div class="w-full h-full bg-panel select-none overscroll-none overflow-hidden flex flex-col"><TopBar id={props.threadId()} title={props.title()} /><divdiff --git a/js/app/packages/block-email/component/EmailFormContext.tsx b/js/app/packages/block-email/component/EmailFormContext.tsxindex 3146d8bb3f..cadd1500a3 100644--- a/js/app/packages/block-email/component/EmailFormContext.tsx+++ b/js/app/packages/block-email/component/EmailFormContext.tsx@@ -1,12 +1,9 @@import { logger } from '@observability/logger';+import { createContext, type ParentProps, useContext } from 'solid-js';import {- type Accessor,- createContext,- createMemo,- type ParentProps,- useContext,-} from 'solid-js';-import { createEmailFormState } from './createEmailFormState';+ createEmailFormState,+ type EmailFormStateOptions,+} from './createEmailFormState';type EmailFormContextValue = ReturnType<typeof createEmailFormState>;@@ -16,7 +13,9 @@ type RegistryApi = {const EmailFormRegistryCtx = createContext<RegistryApi>();-export function EmailFormContextProvider(props: ParentProps) {+export function EmailFormContextProvider(+ props: ParentProps<{ formOptions: EmailFormStateOptions }>+) {const map = new Map<string, EmailFormContextValue>();const getOrInit: RegistryApi['getOrInit'] = (key) => {@@ -25,7 +24,7 @@ export function EmailFormContextProvider(props: ParentProps) {}let existing = map.get(key);if (!existing) {- existing = createEmailFormState(key);+ existing = createEmailFormState(key, props.formOptions);map.set(key, existing);}return existing;@@ -48,13 +47,11 @@ export function getEmailFormRegistry(): RegistryApi {return ctx;}-export function getOrInitEmailFormContext(- key: string-): Accessor<EmailFormContextValue> {+export function getOrInitEmailFormContext(key: string): EmailFormContextValue {const ctx = useContext(EmailFormRegistryCtx);if (!ctx)throw new Error('useEmailFormRegistry must be used within EmailFormContextProvider');- return createMemo(() => ctx.getOrInit(key));+ return ctx.getOrInit(key);}diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.tsindex 920753444a..4812a0354d 100644--- a/js/app/packages/block-email/component/createEmailFormState.ts+++ b/js/app/packages/block-email/component/createEmailFormState.ts@@ -1,7 +1,7 @@import { useEmail } from '@service-gql/client';import type { LexicalEditor } from 'lexical';import { createSignal, type Setter } from 'solid-js';-import { createStore } from 'solid-js/store';+import { createStore, reconcile, unwrap } from 'solid-js/store';import { decodeBase64Utf8 } from '../util/decodeBase64';import { TOGGLE_APPEND_EMAIL_THREAD_COMMAND } from '../util/prepareEmailBody';import {@@ -11,7 +11,8 @@ import {} from '../util/recipientConversion';import type { ReplyType } from '../util/replyType';import { getSubjectText } from '../util/subjectText';-import { type EmailRecipient, useEmailContext } from './EmailContext';+import type { EmailRecipient } from './EmailContext';+import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';export type EmailFormRecipients = {to: EmailRecipient[];@@ -34,17 +35,38 @@ export type DraftFormAttachment =fileSize: number;};+export interface EmailFormStateOptions {+ getMessageByID: (id: string) => MessageWithBodyReplyless | undefined;+ getDraftForMessageReply: (id: string) => MessageWithBodyReplyless | undefined;+ onRecipientsChange?: (next: EmailRecipient[]) => void;+}++type EmailFormState = {+ recipients: {+ to: EmailRecipient[];+ cc: EmailRecipient[];+ bcc: EmailRecipient[];+ };+ replyType: ReplyType;+ withQuotedText: boolean;+ subject: string;+ markdownBody: string;+};+/*** Creates a state object for the email form.* @param key - The db_id of the email being replied to.+ * @param options - Required options for the initial state to be calculated from* @returns A state object for the email form.*/-export function createEmailFormState(key: string) {- const emailCtx = useEmailContext();+export function createEmailFormState(+ key?: string,+ options?: EmailFormStateOptions+) {const userEmail = useEmail();- const replyingTo = emailCtx.messages.list().find((m) => m.db_id === key);- const draft = emailCtx.drafts.getDraftForMessage(key);+ const replyingTo = key ? options?.getMessageByID(key) : undefined;+ const draft = key ? options?.getDraftForMessageReply(key) : undefined;const draftContainsAppendedReply = () => {const encoded = draft?.body_html_sanitized;@@ -56,9 +78,45 @@ export function createEmailFormState(key: string) {return parsed.body.querySelector('div.macro_quote') !== null;};- const [replyAppended, setReplyAppended] = createSignal<boolean>(- draftContainsAppendedReply() ?? false- );+ const getInitialState = () => {+ const replyType =+ (replyingTo?.to.length ?? 0) + (replyingTo?.cc.length ?? 0) > 1+ ? 'reply-all'+ : 'reply';++ let initialSubject = draft?.subject;++ if (initialSubject == null) {+ initialSubject = getSubjectText(replyingTo, replyType);+ }++ let initialRecipients: EmailFormRecipients = { to: [], cc: [], bcc: [] };++ if (draft) {+ initialRecipients = {+ to: draft.to.map(convertContactInfoToEmailRecipient) ?? [],+ cc: draft.cc.map(convertContactInfoToEmailRecipient) ?? [],+ bcc: draft.bcc.map(convertContactInfoToEmailRecipient) ?? [],+ };+ } else if (replyingTo) {+ initialRecipients =+ replyType === 'reply-all'+ ? getReplyAllRecipients(replyingTo, userEmail() ?? '')+ : getReplyRecipientsFromParent(replyingTo, userEmail() ?? '');+ }++ return {+ recipients: initialRecipients,+ replyType,+ withQuotedText: draftContainsAppendedReply(),+ subject: initialSubject,+ markdownBody: '',+ } satisfies EmailFormState;+ };++ const [state, setState] = createStore<EmailFormState>({+ ...getInitialState(),+ });const [onDirtyCb, setOnDirtyCb] = createSignal<(() => void) | undefined>();const [onReplyTypeAppliedCb, setOnReplyTypeAppliedCb] = createSignal<@@ -70,10 +128,6 @@ export function createEmailFormState(key: string) {ReplyType | undefined>(undefined);- const [replyType, setReplyTypeInner] = createSignal<ReplyType | undefined>(- undefined- );-const [shouldFocusInput, setShouldFocusInput] = createSignal(false);// TODO: Replace this signal with a memo deriving the attachments from the draft data@@ -89,91 +143,55 @@ export function createEmailFormState(key: string) {})) ?? []);- const initialReplyType: ReplyType | undefined = replyingTo- ? (replyingTo.to.length ?? 0) + (replyingTo.cc.length ?? 0) > 1- ? 'reply-all'- : 'reply'- : undefined;-- const initialRecipients: EmailFormRecipients = draft- ? {- to: draft.to.map(convertContactInfoToEmailRecipient) ?? [],- cc: draft.cc.map(convertContactInfoToEmailRecipient) ?? [],- bcc: draft.bcc.map(convertContactInfoToEmailRecipient) ?? [],- }- : replyingTo && initialReplyType- ? initialReplyType === 'reply-all'- ? getReplyAllRecipients(replyingTo, userEmail() ?? '')- : getReplyRecipientsFromParent(replyingTo, userEmail() ?? '')- : { to: [], cc: [], bcc: [] };-- const [recipients, setRecipientsInner] = createStore<EmailFormRecipients>({- to: initialRecipients.to,- cc: initialRecipients.cc,- bcc: initialRecipients.bcc,- });-// A wrapper around setRecipientsInner that runs the side-effects alongside setting the storeconst setRecipients = (field: keyof EmailFormRecipients,- value: EmailRecipient[] | ((prev: EmailRecipient[]) => EmailRecipient[])+ value: EmailRecipient[]) => {- const next = typeof value === 'function' ? value(recipients[field]) : value;- setRecipientsInner(field, next);+ setState('recipients', field, value);callDirty();+ const recipients = state.recipients;const all = [...recipients.to, ...recipients.cc, ...recipients.bcc];- emailCtx.onRecipientsChange(all);+ options?.onRecipientsChange?.(unwrap(all));};- const initialSubject =- draft?.subject ??- getSubjectText(- replyingTo,- (replyingTo?.to.length ?? 0) + (replyingTo?.cc.length ?? 0) > 1- ? 'reply-all'- : 'reply'- ) ??- '';-- const [subject, setSubjectInner] = createSignal<string>(initialSubject);-const setSubject: Setter<string> = (value) => {- const result = setSubjectInner(value);+ const result = setState('subject', value);callDirty();return result;};// A wrapper around setReplyTypeInner that runs the side-effects alongside setting the signal- type ReplySetter = typeof setReplyTypeInner;- const setReplyType = (...args: Parameters<ReplySetter>) => {- const rt = setReplyTypeInner(...args);+ const setReplyType = (next: ReplyType) => {+ setState('replyType', next);+ const rt = state.replyType;const msg = replyingTo;if (msg) {- const calculated =- rt === 'reply-all'- ? getReplyAllRecipients(msg, userEmail() ?? '')- : rt === 'reply'- ? getReplyRecipientsFromParent(msg, userEmail() ?? '')- : { to: [], cc: [], bcc: [] };+ let calculated: EmailFormRecipients = { to: [], cc: [], bcc: [] };++ switch (rt) {+ case 'reply-all': {+ calculated = getReplyAllRecipients(msg, userEmail() ?? '');+ break;+ }+ case 'reply': {+ calculated = getReplyRecipientsFromParent(msg, userEmail() ?? '');+ }+ }setRecipients('to', calculated.to ?? []);setRecipients('cc', calculated.cc ?? []);setRecipients('bcc', calculated.bcc ?? []);- if (rt) {- setSubject(getSubjectText(msg, rt));-- if (rt === 'forward') {- setReplyAppended(true);- capturedEditor()?.dispatchCommand(- TOGGLE_APPEND_EMAIL_THREAD_COMMAND,- {- replyingTo: replyingTo,- replyType: rt,- visible: true,- }- );- }+ setSubject(getSubjectText(msg, rt));++ if (rt === 'forward') {+ setState('withQuotedText', true);+ capturedEditor()?.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {+ replyingTo: replyingTo,+ replyType: rt,+ visible: true,+ });}}@@ -188,27 +206,13 @@ export function createEmailFormState(key: string) {};const reset = () => {- setReplyAppended(draftContainsAppendedReply() ?? false);-- // Restore reply type first without side effects that recalc recipients- setReplyTypeInner(initialReplyType);- setLastReplyTypeApplied(initialReplyType);-- // Restore recipients to their initial values (draft or computed)- setRecipientsInner('to', initialRecipients.to);- setRecipientsInner('cc', initialRecipients.cc);- setRecipientsInner('bcc', initialRecipients.bcc);+ setState(reconcile({ ...getInitialState() }));+ const recipients = state.recipients;// Notify context of the full recipient list after reset- const all = [- ...initialRecipients.to,- ...initialRecipients.cc,- ...initialRecipients.bcc,- ];- emailCtx.onRecipientsChange(all);-- // Restore subject and input focus- setSubjectInner(initialSubject);+ const all = [...recipients.to, ...recipients.cc, ...recipients.bcc];+ options?.onRecipientsChange?.(unwrap(all));+setShouldFocusInput(false);setAttachments([]);@@ -219,13 +223,13 @@ export function createEmailFormState(key: string) {const value = {draft,- replyAppended,- setReplyAppended,- recipients,+ replyAppended: () => state.withQuotedText,+ setReplyAppended: (next: boolean) => setState('withQuotedText', next),+ recipients: () => state.recipients,setRecipients,- subject,+ subject: () => state.subject,setSubject,- replyType,+ replyType: () => state.replyType,setReplyType,shouldFocusInput,setShouldFocusInput,@@ -235,7 +239,7 @@ export function createEmailFormState(key: string) {},setOnReplyTypeApplied: (cb?: (rt: ReplyType | undefined) => void) => {setOnReplyTypeAppliedCb(() => cb);- const rt = lastReplyTypeApplied() ?? replyType();+ const rt = lastReplyTypeApplied() ?? state.replyType;if (cb && rt !== undefined) queueMicrotask(() => cb(rt));},setCapturedEditor: (editor: LexicalEditor) => {diff --git a/js/app/packages/block-email/constants.ts b/js/app/packages/block-email/constants.tsindex 30123ad126..a1b8e01b87 100644--- a/js/app/packages/block-email/constants.ts+++ b/js/app/packages/block-email/constants.ts@@ -3,3 +3,5 @@ export const URL_PARAMS = {};export const MACRO_EMAIL_SIGNATURE = '-- Sent with Macro';++export const MAX_ATTACHMENTS_BYTES_SIZE = 18_000_000;diff --git a/js/app/packages/core/component/ForwardToChannel.tsx b/js/app/packages/core/component/ForwardToChannel.tsxindex b2d160694c..8cce5e0665 100644--- a/js/app/packages/core/component/ForwardToChannel.tsx+++ b/js/app/packages/core/component/ForwardToChannel.tsx@@ -259,7 +259,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {<RecipientSelector<'user' | 'contact' | 'channel'>placeholder="To: Email Or Group"setSelectedOptions={setSelectedOptions}- selectedOptions={selectedOptions}+ selectedOptions={selectedOptions()}triedToSubmit={triedToSubmit}options={destinationOptions}triggerMode="input"diff --git a/js/app/packages/core/component/NewMessage.tsx b/js/app/packages/core/component/NewMessage.tsxindex ae0cc58cbd..f82d757556 100644--- a/js/app/packages/core/component/NewMessage.tsx+++ b/js/app/packages/core/component/NewMessage.tsx@@ -213,7 +213,7 @@ export function NewMessage(props: NewMessageProps) {<div class="flex flex-col p-2 gap-2"><RecipientSelector<'user' | 'contact' | 'channel'>options={destinationOptions}- selectedOptions={selectedOptions}+ selectedOptions={selectedOptions()}setSelectedOptions={setSelectedOptions}placeholder="Add by email or channel"triedToSubmit={triedToSubmit}diff --git a/js/app/packages/core/component/RecipientSelector.tsx b/js/app/packages/core/component/RecipientSelector.tsxindex 82a19f6b04..49ebe0f6c2 100644--- a/js/app/packages/core/component/RecipientSelector.tsx+++ b/js/app/packages/core/component/RecipientSelector.tsx@@ -37,7 +37,6 @@ import {type JSX,Match,onMount,- type Setter,Switch,} from 'solid-js';import { type VirtualizerHandle, VList } from 'virtua/solid';@@ -209,8 +208,8 @@ function RecipientComboboxItem(props: RecipientComboboxItemProps): JSX.Element {type RecipientSelectorProps<K extends CombinedRecipientKind> = {options: Accessor<CombinedRecipientItem<K>[]>;- selectedOptions: Accessor<WithCustomUserInput<K>[]>;- setSelectedOptions: Setter<WithCustomUserInput<K>[]>;+ selectedOptions: WithCustomUserInput<K>[];+ setSelectedOptions: (next: WithCustomUserInput<K>[]) => void;// If you provide triedToSubmit, the component will show an error message if no options are selected and triedToSubmit is truetriedToSubmit?: Accessor<boolean>;placeholder?: string | JSX.Element;@@ -268,7 +267,7 @@ export function RecipientSelector<K extends CombinedRecipientKind>(}const placeholderText = () => {- return props.selectedOptions().length === 0+ return props.selectedOptions.length === 0? 'Select recipients': 'select more recipients';};@@ -321,7 +320,7 @@ export function RecipientSelector<K extends CombinedRecipientKind>(const invalid = createMemo(() =>- (props.triedToSubmit?.() ?? false) && props.selectedOptions().length === 0+ (props.triedToSubmit?.() ?? false) && props.selectedOptions.length === 0);const options = createMemo(() => {@@ -378,7 +377,7 @@ export function RecipientSelector<K extends CombinedRecipientKind>(() => {});- const selectedLen = () => props.selectedOptions().length;+ const selectedLen = () => props.selectedOptions.length;const onInputChange = (next: string) => {setInputValue(next);@@ -408,12 +407,12 @@ export function RecipientSelector<K extends CombinedRecipientKind>(optionValue={getRecipientOptionValue}optionTextValue={getRecipientOptionTextValue}optionDisabled={getOptionDisabled}- value={props.selectedOptions() as CombinedRecipientItem[]}+ value={props.selectedOptions as CombinedRecipientItem[]}onChange={debouncedHandleChange}onInputChange={onInputChange}shouldFocusWrapplaceholder={- props.selectedOptions()?.length === 0+ props.selectedOptions?.length === 0? (props.placeholder ?? placeholderText()): undefined}