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 editing and sending email drafts when there is no thread (#1005)

dev-rbf5ec767120c8
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index 24c44a8e6e..581da84f93 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -144,8 +144,10 @@ function RecipientList(props: {
}
export function BaseInput(props: {
- replyingTo: Accessor<MessageWithBodyReplyless>;
+ replyingTo: Accessor<MessageWithBodyReplyless | undefined>;
+ // TODO: Remove `newMessage` props. It's not used...
newMessage?: boolean;
+ isEditingExisting?: boolean;
draft?: MessageWithBodyReplyless;
preloadedBody?: string;
preloadedHtml?: string;
@@ -156,9 +158,37 @@ export function BaseInput(props: {
markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
}) {
const ctx = useEmailContext();
- const form = createMemo(() =>
- getOrInitEmailFormContext(props.replyingTo().db_id!)
- );
+ const form = createMemo(() => {
+ const replyingTo = props.replyingTo();
+
+ // If neither `replyingTo` or `draft` exist, we'll have an empty
+ // initial state
+ if (!replyingTo && !props.draft) {
+ return getOrInitEmailFormContext();
+ }
+
+ // If we have `replyingTo`, we're going to be
+ // creating a reply to a message so we can derive our state
+ // from the `replyingTo` and a possible existing draft
+ if (replyingTo && replyingTo.db_id) {
+ return getOrInitEmailFormContext({
+ type: 'replying_to',
+ messageID: replyingTo.db_id,
+ });
+ }
+
+ // If we only have the draft available, then we're most likely
+ // editing a draft in a new thread with no other messages
+ if (props.draft && props.draft.db_id) {
+ return getOrInitEmailFormContext({
+ type: 'draft',
+ messageID: props.draft.db_id,
+ });
+ }
+
+ // Fallback to empty state
+ return getOrInitEmailFormContext();
+ });
const blockId = useBlockId();
const emailLinksQuery = useEmailLinksQuery();
@@ -166,7 +196,6 @@ export function BaseInput(props: {
const [expandedRecipientsRef, setExpandedRecipientsRef] =
createSignal<HTMLDivElement>();
const [editor, setEditor] = createSignal<LexicalEditor>();
- const [showSubject, _] = createSignal(props.newMessage ?? false);
const [showExpandedRecipients, setShowExpandedRecipients] =
createSignal<boolean>(false);
const [isDragging, setIsDragging] = createSignal<boolean>();
@@ -482,10 +511,17 @@ export function BaseInput(props: {
!hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
);
- const prepared = prepareEmailBody(currentEditor, {
- replyType: effectiveReplyType(),
- replyingTo: props.replyingTo(),
- });
+ const replyingTo = props.replyingTo();
+
+ const prepared = prepareEmailBody(
+ currentEditor,
+ replyingTo
+ ? {
+ replyType: effectiveReplyType(),
+ replyingTo,
+ }
+ : undefined
+ );
if (!prepared) {
return;
}
@@ -887,8 +923,10 @@ export function BaseInput(props: {
</div>
</Show>
</div>
- <div class={`${showSubject() ? 'flex' : 'hidden'} flex-row items-center`}>
- <div class="text-xs min-w-16">Subject</div>
+ <div
+ class={`${props.isEditingExisting || props.newMessage ? 'flex' : 'hidden'} flex-row items-center`}
+ >
+ <div class="text-sm min-w-16 pl-4">Subject</div>
<input
type="text"
class="flex-1 text-sm bg-transparent outline-none border-0 px-3 py-1"
diff --git a/js/app/packages/block-email/component/Block.tsx b/js/app/packages/block-email/component/Block.tsx
index 8d567e1496..e7672d7301 100644
--- a/js/app/packages/block-email/component/Block.tsx
+++ b/js/app/packages/block-email/component/Block.tsx
@@ -5,6 +5,7 @@ import { EmailDebouncedReadMarker } from '@notifications';
import { createMemo, onMount, Show, Suspense } from 'solid-js';
import { blockDataSignal } from '../signal/emailBlockData';
import { EmailView } from './Email';
+import { useThreadQuery } from '@queries/email/thread';
const { track, TrackingEvents } = withAnalytics();
@@ -12,38 +13,44 @@ export default function BlockEmail() {
const blockData = blockDataSignal.get;
const notificationSource = useGlobalNotificationSource();
- const title = createMemo(() => {
- const data = blockData();
+ const threadId = createMemo(() => blockData()?.thread?.db_id ?? '');
+
+ const threadQuery = useThreadQuery(threadId, () => ({
+ enabled: !!threadId(),
+ }));
+
+ const title = () => {
+ const data = threadQuery.data;
if (!data || !data.thread || data.thread.messages.length === 0) return '';
if (data.thread.messages[0].subject?.length === 0) return '[No subject]';
return data.thread.messages[0].subject!;
- });
-
- const threadId = createMemo(() => blockData()?.thread?.db_id ?? '');
+ };
onMount(() => {
track(TrackingEvents.BLOCKEMAIL.OPEN);
});
return (
- <DocumentBlockContainer title={title() ?? 'Email'}>
- <div class="size-full bracket-never" tabIndex={-1}>
- <Show when={blockData()}>
- <Show when={threadId()}>
- {(id) => (
- <>
- <EmailDebouncedReadMarker
- notificationSource={notificationSource}
- threadId={id()}
- />
- <Suspense>
- <EmailView title={title} threadId={id} />
- </Suspense>
- </>
- )}
+ <Suspense>
+ <DocumentBlockContainer title={title() ?? 'Email'}>
+ <div class="size-full bracket-never" tabIndex={-1}>
+ <Show when={blockData()}>
+ <Show when={threadId()}>
+ {(id) => (
+ <>
+ <EmailDebouncedReadMarker
+ notificationSource={notificationSource}
+ threadId={id()}
+ />
+ <Suspense>
+ <EmailView title={title()} threadId={id} />
+ </Suspense>
+ </>
+ )}
+ </Show>
</Show>
- </Show>
- </div>
- </DocumentBlockContainer>
+ </div>
+ </DocumentBlockContainer>
+ </Suspense>
);
}
diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsx
index fc9c9175cc..850b2d0bec 100644
--- a/js/app/packages/block-email/component/Compose.tsx
+++ b/js/app/packages/block-email/component/Compose.tsx
@@ -46,7 +46,10 @@ import {
$appendWatermarkNodeToLast,
$removeAllWatermarkNodes,
} from '@lexical-core';
-import { prepareEmailBody } from '@block-email/util/prepareEmailBody';
+import {
+ clearEmailBody,
+ prepareEmailBody,
+} from '@block-email/util/prepareEmailBody';
import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';
import {
deleteEmailDraft,
@@ -57,6 +60,8 @@ import {
useUploadDraftAttachmentsMutation,
} from '@queries/email/attachment';
import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
+import { useMaybeEmailContext } from '@block-email/component/EmailContext';
+import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';
const DRAFT_DEBOUNCE_MS = 1000;
@@ -82,7 +87,11 @@ type EmailComposeElementRefs = {
messageInput: HTMLElement | undefined;
};
-export function EmailCompose() {
+type EmailComposeProps = {
+ draftID?: string;
+};
+
+export function EmailCompose(props: EmailComposeProps) {
const hasPaidAccess = useHasPaidAccess();
const { showPaywall } = usePaywallState();
@@ -124,14 +133,31 @@ export function EmailCompose() {
const { users: destinationOptions } = useCombinedRecipients();
- const form = createEmailFormState();
+ const emailContext = useMaybeEmailContext();
+
+ const form = createEmailFormState(
+ props.draftID
+ ? {
+ type: 'draft',
+ messageID: props.draftID,
+ }
+ : undefined,
+ emailContext
+ ? {
+ getMessageByID: (id) =>
+ emailContext.messages.unfiltered().find((m) => m.db_id === id),
+ getDraftForMessageReply: emailContext.drafts.getDraftForMessage,
+ onRecipientsChange: emailContext.onRecipientsChange,
+ }
+ : undefined
+ );
const [editor, setEditor] = createSignal<LexicalEditor | undefined>();
const [content, setContent] = createSignal('');
- const [currentDraftID, setCurrentDraftID] = createSignal<
- string | undefined
- >();
+ const [currentDraftID, setCurrentDraftID] = createSignal<string | undefined>(
+ props.draftID
+ );
const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();
@@ -186,6 +212,7 @@ export function EmailCompose() {
const draftResponse = await saveEmailDraft({
...draftToSave,
+ db_id: currentDraftID(),
link_id: linkID,
});
@@ -487,12 +514,36 @@ export function EmailCompose() {
cleanupWatermark();
};
+ const resetState = () => {
+ clearEmailBody(editor());
+ setContent('');
+ setCurrentDraftID(undefined);
+ form.clear();
+ };
+
+ const deleteDraftAndReset = async () => {
+ const draftId = currentDraftID();
+ if (draftId) {
+ await deleteEmailDraft(draftId);
+ }
+ resetState();
+ };
+
const withValidationError = (type: EmailComposeErrors) => {
const error = validationError();
if (error?.type === type) return error;
return undefined;
};
+ const initialHtml = () => {
+ const draft = form.draft;
+ if (!draft || !draft.body_html_sanitized) return;
+
+ const decodedHtml = decodeBase64Utf8(draft.body_html_sanitized);
+
+ return decodedHtml;
+ };
+
return (
<>
<SplitHeaderLeft>
@@ -713,12 +764,15 @@ export function EmailCompose() {
<ComposeEmailInput
captureEditor={setEditor}
inputRef={registerRef('messageInput')}
+ initialHtml={initialHtml()}
onContentChange={onContentChange}
onAddAttachments={onAddAttachments}
onRemoveAttachment={handleRemoveAttachment}
attachments={form.attachments.list()}
onSubmit={onSubmit}
isSubmitting={sendMutation.isPending}
+ hasDraft={currentDraftID() != null}
+ onDraftDeletePress={deleteDraftAndReset}
disabled={hasLinkError() || sendMutation.isPending}
/>
<Show when={withValidationError('no_message')}>
diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsx
index 8a6f533b35..2f9c67bced 100644
--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx
+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx
@@ -1,4 +1,5 @@
import { useSplitPanel } from '@app/component/split-layout/layoutUtils';
+import Trash from '@icon/regular/trash.svg';
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
import { MAX_ATTACHMENTS_BYTES_SIZE } from '@block-email/constants';
@@ -42,9 +43,11 @@ type ComposeEmailInputProps = {
captureEditor?: (editor: LexicalEditor) => void;
onSubmit: () => void;
disabled?: boolean;
- loading?: boolean;
isSubmitting?: boolean;
+ hasDraft?: boolean;
+ onDraftDeletePress?: VoidFunction;
attachments?: DraftFormAttachment[];
+ initialHtml?: string;
onAddAttachments?: (attachments: DraftFormAttachment[]) => void;
onRemoveAttachment?: (attachment: DraftFormAttachment) => void;
onContentChange?: (content: string) => void;
@@ -220,6 +223,7 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
<MarkdownTextarea
domRef={props.inputRef}
captureEditor={captureEditor}
+ initialHtml={props.initialHtml}
class="text-sm break-words text-ink"
editable={() => !props.disabled}
placeholder="Use `@` to reference files"
@@ -300,17 +304,26 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
setShowFormatRibbon(!showFormatRibbon());
}}
/>
+ <Show when={props.hasDraft}>
+ <Button
+ onclick={props.onDraftDeletePress}
+ tooltip="Delete draft"
+ class="aspect-square *:h-5 p-1"
+ >
+ <Trash />
+ </Button>
+ </Show>
</div>
<button
type="button"
- disabled={props.loading || props.isSubmitting || props.disabled}
+ disabled={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={!props.loading && !props.isSubmitting}
+ when={!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.tsx
index 4a93343588..3aba4b07a6 100644
--- a/js/app/packages/block-email/component/Email.tsx
+++ b/js/app/packages/block-email/component/Email.tsx
@@ -16,8 +16,10 @@ import {
type Accessor,
createEffect,
createMemo,
+ Match,
onMount,
Show,
+ Switch,
untrack,
} from 'solid-js';
import { isScrollingToMessage } from '../signal/scrollState';
@@ -27,13 +29,14 @@ import { EmailFormContextProvider } from './EmailFormContext';
import { EmailInput } from './EmailInput';
import { MessageList } from './MessageList';
import { TopBar } from './TopBar';
+import { EmailCompose } from '@block-email/component/Compose';
const TARGET_MESSAGE_HIGHLIGHT_MS = 800;
const SCROLL_ANIMATION_MS = 1000;
const SCROLL_AFTER_SEND_DELAY_MS = 100;
type EmailViewProps = {
- title: Accessor<string>;
+ title: string;
threadId: Accessor<string>;
};
@@ -394,62 +397,106 @@ function EmailContent(props: EmailViewProps) {
hide: true,
});
+ const emailReplyInfo = createMemo(() => {
+ const filtered = context.messages.list();
+
+ // If there are non draft messages in this thread, the bottom input will
+ // be for sending a reply to the last message
+ if (filtered.length !== 0) {
+ const lastMessage = filtered.at(-1);
+ if (!lastMessage || !lastMessage.db_id) return;
+ return {
+ replyingTo: lastMessage,
+ draft: context.drafts.getDraftForMessage(lastMessage.db_id),
+ };
+ }
+
+ // Otherwise, if the other messages in the thread are drafts,
+ // the bottom input will be for editing and sending the latest/last draft
+ const unfiltered = context.messages.unfiltered();
+
+ if (unfiltered.length === 0) return;
+
+ const latest = unfiltered.at(-1);
+
+ if (!latest || !latest.is_draft) return;
+
+ return { replyingTo: undefined, draft: latest };
+ });
+
return (
- <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()} />
- <div
- class="w-full flex-1 flex flex-col items-center overflow-hidden"
- ref={context.registerMessagesContainer}
- >
- <MessageList
- initialLoadComplete={context.initialLoadComplete()}
- title={props.title()}
- />
- <CustomScrollbar reverse scrollContainer={context.messagesListRef} />
- </div>
- <FloatingInputLoader
- isLoading={context.query.isFetching}
- loadingText="Loading messages"
- class="top-2"
- />
- <Show
- when={
- context.permissions().isOwner &&
- context.drafts.initialDraftsSettled() &&
- context.messages.list().at(-1)
- }
- >
- {(lastMessage) => {
- return (
- <div class="shrink-0 w-full px-4 pb-2">
- <div class="relative w-full flex flex-row justify-center bg-panel macro-message-width mx-auto">
- <EmailInput
- replyingTo={lastMessage}
- draft={
- lastMessage().db_id
- ? context.drafts.getDraftForMessage(
- lastMessage().db_id!
- )
- : undefined
- }
- markdownDomRef={(el) => {
- markdownDomRef = el;
- }}
- />
- </div>
- </div>
- );
+ <Switch>
+ <Match
+ when={
+ emailReplyInfo()?.replyingTo == null &&
+ emailReplyInfo()?.draft?.db_id != null &&
+ emailReplyInfo()?.draft
+ }
+ >
+ {(draft) => <EmailCompose draftID={draft().db_id!} />}
+ </Match>
+
+ <Match when={true}>
+ <EmailFormContextProvider
+ formOptions={{
+ getMessageByID: (id) =>
+ context.messages.unfiltered().find((m) => m.db_id === id),
+ getDraftForMessageReply: context.drafts.getDraftForMessage,
+ onRecipientsChange: context.onRecipientsChange,
}}
- </Show>
- </div>
- </EmailFormContextProvider>
+ >
+ <div class="w-full h-full bg-panel select-none overscroll-none overflow-hidden flex flex-col">
+ <TopBar
+ id={props.threadId()}
+ title={props.title}
+ isDraft={
+ emailReplyInfo()?.replyingTo == null &&
+ emailReplyInfo()?.draft !== null
+ }
+ />
+ <div
+ class="w-full flex-1 flex flex-col items-center overflow-hidden"
+ ref={context.registerMessagesContainer}
+ >
+ <MessageList
+ initialLoadComplete={context.initialLoadComplete()}
+ title={props.title}
+ />
+ <CustomScrollbar
+ reverse
+ scrollContainer={context.messagesListRef}
+ />
+ </div>
+ <Show
+ when={
+ context.permissions().isOwner &&
+ context.drafts.initialDraftsSettled() &&
+ emailReplyInfo()
+ }
+ >
+ {(info) => {
+ return (
+ <div class="shrink-0 w-full px-4 pb-2">
+ <div class="relative w-full flex flex-row justify-center bg-panel macro-message-width mx-auto">
+ <FloatingInputLoader
+ isLoading={context.query.isFetching}
+ loadingText="Loading messages"
+ />
+ <EmailInput
+ replyingTo={() => info().replyingTo}
+ draft={info().draft}
+ markdownDomRef={(el) => {
+ markdownDomRef = el;
+ }}
+ />
+ </div>
+ </div>
+ );
+ }}
+ </Show>
+ </div>
+ </EmailFormContextProvider>
+ </Match>
+ </Switch>
);
}
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index 148135c507..7962b7bfe9 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -101,6 +101,23 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
select(data) {
const messages = data.pages.flatMap((t) => t.messages);
+ // Sort all messages by recency
+ messages.sort((a, b) => {
+ if (a.internal_date_ts && b.internal_date_ts) {
+ return (
+ new Date(a.internal_date_ts).getTime() -
+ new Date(b.internal_date_ts).getTime()
+ );
+ }
+ // Below is fallback for when internal_date_ts is not set
+ else if (a.sent_at && b.sent_at) {
+ return (
+ new Date(a.sent_at).getTime() - new Date(b.sent_at).getTime()
+ );
+ }
+ return 0;
+ });
+
const filtered = [];
const messageDraftMap: Record<string, MessageWithBodyReplyless> = {};
@@ -121,22 +138,6 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
messageDraftMap[replyingToId] = message;
}
- filtered.sort((a, b) => {
- if (a.internal_date_ts && b.internal_date_ts) {
- return (
- new Date(a.internal_date_ts).getTime() -
- new Date(b.internal_date_ts).getTime()
- );
- }
- // Below is fallback for when internal_date_ts is not set
- else if (a.sent_at && b.sent_at) {
- return (
- new Date(a.sent_at).getTime() - new Date(b.sent_at).getTime()
- );
- }
- return 0;
- });
-
return {
...data.pages[0],
messages: messages,
@@ -460,3 +461,7 @@ export function useEmailContext() {
}
return ctx;
}
+
+export function useMaybeEmailContext() {
+ return useContext(EmailContext);
+}
diff --git a/js/app/packages/block-email/component/EmailFormContext.tsx b/js/app/packages/block-email/component/EmailFormContext.tsx
index cadd1500a3..11d2eac3a8 100644
--- a/js/app/packages/block-email/component/EmailFormContext.tsx
+++ b/js/app/packages/block-email/component/EmailFormContext.tsx
@@ -1,4 +1,3 @@
-import { logger } from '@observability/logger';
import { createContext, type ParentProps, useContext } from 'solid-js';
import {
createEmailFormState,
@@ -7,8 +6,16 @@ import {
type EmailFormContextValue = ReturnType<typeof createEmailFormState>;
+type FormAccessKey =
+ | { type: 'replying_to'; messageID: string }
+ | { type: 'draft'; messageID: string };
+
+const stringifyKey = (key: FormAccessKey) => {
+ return `${key.type}_${key.messageID}`;
+};
+
type RegistryApi = {
- getOrInit: (key: string) => EmailFormContextValue;
+ getOrInit: (key?: FormAccessKey) => EmailFormContextValue;
};
const EmailFormRegistryCtx = createContext<RegistryApi>();
@@ -20,12 +27,13 @@ export function EmailFormContextProvider(
const getOrInit: RegistryApi['getOrInit'] = (key) => {
if (!key) {
- logger.error('Key is required');
+ return createEmailFormState();
}
- let existing = map.get(key);
+ const stringifiedKey = stringifyKey(key);
+ let existing = map.get(stringifiedKey);
if (!existing) {
existing = createEmailFormState(key, props.formOptions);
- map.set(key, existing);
+ map.set(stringifiedKey, existing);
}
return existing;
};
@@ -47,7 +55,9 @@ export function getEmailFormRegistry(): RegistryApi {
return ctx;
}
-export function getOrInitEmailFormContext(key: string): EmailFormContextValue {
+export function getOrInitEmailFormContext(
+ key?: FormAccessKey
+): EmailFormContextValue {
const ctx = useContext(EmailFormRegistryCtx);
if (!ctx)
throw new Error(
diff --git a/js/app/packages/block-email/component/EmailInput.tsx b/js/app/packages/block-email/component/EmailInput.tsx
index 128fe759da..fe5c171446 100644
--- a/js/app/packages/block-email/component/EmailInput.tsx
+++ b/js/app/packages/block-email/component/EmailInput.tsx
@@ -8,7 +8,7 @@ import { decodeBase64Utf8 } from '../util/decodeBase64';
import { BaseInput } from './BaseInput';
interface EmailInputProps {
- replyingTo: Accessor<MessageWithBodyReplyless>;
+ replyingTo: Accessor<MessageWithBodyReplyless | undefined>;
draft?: MessageWithBodyReplyless;
setShowReply?: Setter<boolean>;
markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
@@ -33,7 +33,7 @@ export function EmailInput(props: EmailInputProps) {
}
return (
- <Show when={props.replyingTo() && ctx.drafts.initialDraftsSettled()}>
+ <Show when={ctx.drafts.initialDraftsSettled()}>
<BaseInput
replyingTo={props.replyingTo}
draft={props.draft}
@@ -42,6 +42,7 @@ export function EmailInput(props: EmailInputProps) {
onMarkDone={ctx.archiveThread}
setShowReply={props.setShowReply}
markdownDomRef={props.markdownDomRef}
+ isEditingExisting={props.replyingTo() == null && props.draft != null}
/>
</Show>
);
diff --git a/js/app/packages/block-email/component/MessageActions.tsx b/js/app/packages/block-email/component/MessageActions.tsx
index 1e9920f25d..0f62e6369b 100644
--- a/js/app/packages/block-email/component/MessageActions.tsx
+++ b/js/app/packages/block-email/component/MessageActions.tsx
@@ -6,6 +6,7 @@ import { useEmail } from '@service-gql/client';
import { Button } from '@ui/components/Button';
import { type Setter, Show } from 'solid-js';
import { getEmailFormRegistry } from './EmailFormContext';
+import type { ReplyType } from '@block-email/util/replyType';
const EMAIL_MESSAGE_ACTIONS = ['reply', 'reply-all', 'forward'] as const;
export type EmailMessageAction = (typeof EMAIL_MESSAGE_ACTIONS)[number];
@@ -39,6 +40,20 @@ export function MessageActions(props: {
return !allActionsHidden;
};
+ const onChangeReplyType = (type: ReplyType) => {
+ return () => {
+ if (!props.isLastMessage) {
+ props.setShowReply(true);
+ }
+ const form = formRegistry.getOrInit({
+ type: 'replying_to',
+ messageID: props.message.db_id ?? '',
+ });
+ form.setReplyType(type);
+ form.setShouldFocusInput(true);
+ };
+ };
+
return (
<div
class="flex flex-row items-center gap-4 transition-opacity"
@@ -55,14 +70,7 @@ export function MessageActions(props: {
<Show when={!props.hiddenActions?.includes('reply')}>
<Button
class="h-8 w-8 p-0 border-0 bg-transparent hover:bg-hover hover-transition-bg text-ink gap-0.5 active:bg-hover active:text-ink active:border-transparent"
- onClick={() => {
- if (!props.isLastMessage) {
- props.setShowReply(true);
- }
- const form = formRegistry.getOrInit(props.message.db_id ?? '');
- form.setReplyType('reply');
- form.setShouldFocusInput(true);
- }}
+ onClick={onChangeReplyType('reply')}
tooltip={<span>Reply</span>}
>
<ArrowBendUpLeft class="h-5 w-5" />
@@ -72,14 +80,7 @@ export function MessageActions(props: {
>
<Button
class="h-8 w-8 p-0 border-0 bg-transparent hover:bg-hover hover-transition-bg text-ink gap-0.5 active:bg-hover active:text-ink active:border-transparent"
- onClick={() => {
- if (!props.isLastMessage) {
- props.setShowReply(true);
- }
- const form = formRegistry.getOrInit(props.message.db_id ?? '');
- form.setReplyType('reply-all');
- form.setShouldFocusInput(true);
- }}
+ onClick={onChangeReplyType('reply-all')}
tooltip={<span>Reply all</span>}
>
<ArrowBendDoubleUpLeft class="h-5 w-5" />
@@ -88,14 +89,7 @@ export function MessageActions(props: {
<Show when={!props.hiddenActions?.includes('forward')}>
<Button
class="h-8 w-8 p-0 border-0 bg-transparent hover:bg-hover hover-transition-bg text-ink gap-0.5 active:bg-hover active:text-ink active:border-transparent"
- onClick={() => {
- if (!props.isLastMessage) {
- props.setShowReply(true);
- }
- const form = formRegistry.getOrInit(props.message.db_id ?? '');
- form.setReplyType('forward');
- form.setShouldFocusInput(true);
- }}
+ onClick={onChangeReplyType('forward')}
tooltip={<span>Forward</span>}
>
<ArrowBendUpRight class="h-5 w-5" />
diff --git a/js/app/packages/block-email/component/TopBar.tsx b/js/app/packages/block-email/component/TopBar.tsx
index 19f102fd81..6d358d1daf 100644
--- a/js/app/packages/block-email/component/TopBar.tsx
+++ b/js/app/packages/block-email/component/TopBar.tsx
@@ -1,5 +1,8 @@
import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
-import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';
+import {
+ SplitHeaderBadge,
+ StaticSplitLabel,
+} from '@app/component/split-layout/components/SplitLabel';
import { SplitToolbarRight } from '@app/component/split-layout/components/SplitToolbar';
import { hasPermissions, Permissions } from '@core/component/SharePermissions';
import { ShareButton } from '@core/component/TopBar/ShareButton';
@@ -8,13 +11,30 @@ import { Show } from 'solid-js';
import { useEmailContext } from './EmailContext';
import { EmailPropertiesModal } from './EmailPropertiesModal';
-export function TopBar(props: { id: string; title: string }) {
+export function TopBar(props: {
+ id: string;
+ title: string;
+ isDraft?: boolean;
+}) {
const email = useEmailContext();
return (
<>
<SplitHeaderLeft>
- <StaticSplitLabel iconType="email" label={props.title} />
+ <StaticSplitLabel
+ iconType="email"
+ label={props.title}
+ badges={
+ props.isDraft
+ ? [
+ <SplitHeaderBadge
+ text="draft"
+ tooltip="This is a Draft Email"
+ />,
+ ]
+ : undefined
+ }
+ />
</SplitHeaderLeft>
<SplitToolbarRight>
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index 4812a0354d..758fc4cc26 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -53,20 +53,46 @@ type EmailFormState = {
markdownBody: string;
};
+const EMPTY_FORM_STATE: EmailFormState = {
+ recipients: {
+ to: [],
+ cc: [],
+ bcc: [],
+ },
+ replyType: 'reply',
+ withQuotedText: false,
+ subject: '',
+ markdownBody: '',
+};
+
/**
* Creates a state object for the email form.
- * @param key - The db_id of the email being replied to.
+ * @param purpose - The purpose of the form. Are we managing the state of a draft reply or just a draft message
* @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,
+ purpose?:
+ | { type: 'replying_to'; messageID: string }
+ | { type: 'draft'; messageID: string },
+
options?: EmailFormStateOptions
) {
const userEmail = useEmail();
- const replyingTo = key ? options?.getMessageByID(key) : undefined;
- const draft = key ? options?.getDraftForMessageReply(key) : undefined;
+ let replyingTo: MessageWithBodyReplyless | undefined;
+
+ if (purpose?.type === 'replying_to') {
+ replyingTo = options?.getMessageByID(purpose.messageID);
+ }
+
+ let draft: MessageWithBodyReplyless | undefined;
+
+ if (purpose?.type === 'draft') {
+ draft = options?.getMessageByID(purpose.messageID);
+ } else if (purpose?.type === 'replying_to') {
+ draft = options?.getDraftForMessageReply(purpose?.messageID);
+ }
const draftContainsAppendedReply = () => {
const encoded = draft?.body_html_sanitized;
@@ -119,10 +145,13 @@ export function createEmailFormState(
});
const [onDirtyCb, setOnDirtyCb] = createSignal<(() => void) | undefined>();
+
const [onReplyTypeAppliedCb, setOnReplyTypeAppliedCb] = createSignal<
((rt: ReplyType | undefined) => void) | undefined
>();
+
const [capturedEditor, setCapturedEditor] = createSignal<LexicalEditor>();
+
// We track the last reply type applied to replay against the current state when setOnReplyTypeApplied is attached
const [lastReplyTypeApplied, setLastReplyTypeApplied] = createSignal<
ReplyType | undefined
@@ -143,7 +172,6 @@ export function createEmailFormState(
})) ?? []
);
- // A wrapper around setRecipientsInner that runs the side-effects alongside setting the store
const setRecipients = (
field: keyof EmailFormRecipients,
value: EmailRecipient[]
@@ -161,7 +189,6 @@ export function createEmailFormState(
return result;
};
- // A wrapper around setReplyTypeInner that runs the side-effects alongside setting the signal
const setReplyType = (next: ReplyType) => {
setState('replyType', next);
const rt = state.replyType;
@@ -221,6 +248,22 @@ export function createEmailFormState(
callDirty();
};
+ const clear = () => {
+ setState(reconcile({ ...EMPTY_FORM_STATE }));
+ const recipients = state.recipients;
+
+ // Notify context of the full recipient list after reset
+ const all = [...recipients.to, ...recipients.cc, ...recipients.bcc];
+ options?.onRecipientsChange?.(unwrap(all));
+
+ setShouldFocusInput(false);
+
+ setAttachments([]);
+
+ // Mark as dirty to propagate change
+ callDirty();
+ };
+
const value = {
draft,
replyAppended: () => state.withQuotedText,
@@ -234,6 +277,7 @@ export function createEmailFormState(
shouldFocusInput,
setShouldFocusInput,
reset,
+ clear,
setOnDirty: (cb?: () => void) => {
setOnDirtyCb(() => cb);
},
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index 9254fdd6c5..30c53f60e6 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -124,7 +124,7 @@ export function useThreadQuery<Options extends UseThreadQueryOptions>(
threadId: Accessor<string>,
options: Accessor<Options>
): UseInfiniteQueryResult<
- Options['select'] extends undefined
+ Extract<Options, { select: unknown }> extends never
? ThreadQueryData
: ReturnType<NonNullable<Options['select']>>,
Error