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
chore(email): Refactor email compose (#2263)
Eric Hayesfbcdbe8c27bb
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 1e24952916..d697f885d3 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -1,19 +1,19 @@+import { useAnalytics } from '@app/component/analytics-context';+import { getDefaultListViewPreset } from '@app/component/app-sidebar/soup-filter-presets';+import { SoupView } from '@app/component/next-soup/soup-view/soup-view';import { ChannelCompose } from '@block-channel/component/Compose';import { ComposeTask } from '@block-md/component/ComposeTask';import { useIsAuthenticated } from '@core/auth';import { LoadingBlock } from '@core/component/LoadingBlock';import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';+import { useUserContext } from '@core/context/user';import type { ViewId } from '@core/types/view';+import NotificationRoute from '@notifications/components/NotificationRoute';import { type Component, type JSXElement, lazy, onMount, Show } from 'solid-js';-import { EmailCompose } from '../../../block-email/component/Compose';+import { EmailCompose } from '../../../block-email/component/compose/Compose';import { SettingsPanelComponentWrapper } from '../settings/Settings';-import NotificationRoute from '@notifications/components/NotificationRoute';-import { SoupView } from '@app/component/next-soup/soup-view/soup-view';-import { getDefaultListViewPreset } from '@app/component/app-sidebar/soup-filter-presets';-import { useUserContext } from '@core/context/user';-import { useSplitPanelOrThrow } from './layoutUtils';import type { SplitContent } from './layoutManager';-import { useAnalytics } from '@app/component/analytics-context';+import { useSplitPanelOrThrow } from './layoutUtils';function usePageViewTracking(pageTitle: string) {const analytics = useAnalytics();diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxdeleted file mode 100644index 3c93015b88..0000000000--- a/js/app/packages/block-email/component/Compose.tsx+++ /dev/null@@ -1,1110 +0,0 @@-import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';-import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';-import {- SplitHeaderBadge,- StaticSplitLabel,-} from '@app/component/split-layout/components/SplitLabel';-import { useSplitLayout } from '@app/component/split-layout/layout';-import { useHasPaidAccess } from '@core/auth';-import { CircleSpinner } from '@core/component/CircleSpinner';-import { ClippedPanel } from '@core/component/ClippedPanel';-import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';-import { RecipientSelector } from '@core/component/RecipientSelector';-import { toast } from '@core/component/Toast/Toast';-import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';-import { TOKENS } from '@core/hotkey/tokens';-import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';-import {- type ContactInfo,- tryMacroId,- useDisplayName,- type WithCustomUserInput,-} from '@core/user';--import { useEmailLinksQuery } from '@queries/email/link';-import {- useSendMessageMutation,- useUnscheduleMessageMutation,-} from '@queries/email/thread';-import {- type Accessor,- createEffect,- createMemo,- createSignal,- type JSX,- on,- onMount,- Show,- Suspense,-} from 'solid-js';-import { beveledCorners } from '../../core/signal/beveledCorners';-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 {- clearEmailBody,- hasDraftContent,- prepareEmailBody,-} from '@block-email/util/prepareEmailBody';-import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';-import {- useDeleteDraftMutation,- useSaveDraftMutation,-} from '@queries/email/draft';-import {- useRemoveDraftAttachmentMutation,- useRemoveForwardedAttachmentMutation,- useUploadDraftAttachmentsMutation,-} from '@queries/email/attachment';-import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';-import {- type EmailRecipient,- useMaybeEmailContext,-} from '@block-email/component/EmailContext';-import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';-import { plainTextToHtml } from '@block-email/util/plainTextToHtml';-import { stickyGate } from '@core/util/debounce';-import { invalidateSoupEntity } from '@queries/soup/cache';-import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';-import { isMobile } from '@core/mobile/isMobile';-import { $generateHtmlFromNodes } from '@lexical/html';-import type { EmailFormRecipients } from '@block-email/component/createEmailFormState';-import { unwrap } from 'solid-js/store';-import { emailClient } from '@service-email/client';-import { queryClient } from '@queries/client';-import { emailKeys } from '@queries/email/keys';--const DRAFT_DEBOUNCE_MS = 1000;--type UndoComposeSnapshot = {- draftId: string;- recipients: EmailFormRecipients;- subject: string;- bodyHtml: string;- attachments: DraftFormAttachment[];-};--let undoComposeSnapshot: UndoComposeSnapshot | null = null;--type EmailComposeErrors =- | 'no_recipient'- | 'no_message'- | 'no_subject'- | 'no_link';--class EmailComposeError {- constructor(- public type: EmailComposeErrors,- public message: string- ) {}-}--type EmailComposeElementRefs = {- directRecipientsSelector: HTMLElement | undefined;- ccRecipientsSelector: HTMLElement | undefined;- bccRecipientsSelector: HTMLElement | undefined;- containerRef: HTMLElement | undefined;- subjectInput: HTMLElement | undefined;- messageInput: HTMLElement | undefined;-};--type EmailComposeProps = {- draftID?: string;-};--type RecipientFieldId = 'to' | 'cc' | 'bcc';--type DragState = {- recipient: EmailRecipient;- sourceField: RecipientFieldId;-};--function ComposeFieldRow(props: {- label: string;- children: JSX.Element;- fieldId?: RecipientFieldId;- dragState?: Accessor<DragState | null>;- onRecipientDrop?: (- recipient: EmailRecipient,- sourceField: RecipientFieldId- ) => void;-}) {- const [isDragOver, setIsDragOver] = createSignal(false);-- const handleDragOver = (e: DragEvent) => {- const drag = props.dragState?.();- if (!drag || !props.fieldId || drag.sourceField === props.fieldId) return;- e.preventDefault();- if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';- setIsDragOver(true);- };-- const handleDragLeave = () => {- setIsDragOver(false);- };-- const handleDrop = (e: DragEvent) => {- e.preventDefault();- setIsDragOver(false);- const drag = props.dragState?.();- if (!drag || !props.fieldId || drag.sourceField === props.fieldId) return;- props.onRecipientDrop?.(drag.recipient, drag.sourceField);- };-- return (- <div- class="flex items-center gap-2 border-b border-edge-muted focus-within:border-accent"- classList={{ 'border-accent bg-accent/10': isDragOver() }}- onDragOver={handleDragOver}- onDragLeave={handleDragLeave}- onDrop={handleDrop}- >- <div class="text-sm w-7 shrink-0 text-ink-placeholder/70">- {props.label}- </div>- <div class="flex-1">{props.children}</div>- </div>- );-}--export function EmailCompose(props: EmailComposeProps) {- const hasPaidAccess = useHasPaidAccess();- const emailLinksQuery = useEmailLinksQuery();-- const [refs, setRefs] = createSignal<EmailComposeElementRefs>({- directRecipientsSelector: undefined,- ccRecipientsSelector: undefined,- bccRecipientsSelector: undefined,- containerRef: undefined,- subjectInput: undefined,- messageInput: undefined,- });-- let mobileScrollRef: HTMLDivElement | undefined;-- const registerRef = (name: keyof EmailComposeElementRefs) => {- return (el: HTMLElement) => {- setRefs((p) => ({ ...p, [name]: el }));- };- };-- const [attachComposeHotkeys, composeHotkeyScope] =- useHotkeyDOMScope('compose-email');-- const link = createMemo(() => {- const data = emailLinksQuery.data;- if (data && data.links.length > 0) {- return data.links[0];- }- return undefined;- });-- const hasLinkError = createMemo(() => {- if (emailLinksQuery.isPending) return false;- return (- emailLinksQuery.isError ||- (emailLinksQuery.data && emailLinksQuery.data.links.length === 0)- );- });-- const { users: destinationOptions } = useCombinedRecipients();-- 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>(- props.draftID- );-- // Restore form state from undo-send snapshot if available- const restoredSnapshot =- undoComposeSnapshot?.draftId === props.draftID ? undoComposeSnapshot : null;- if (restoredSnapshot) {- form.setRecipients('to', restoredSnapshot.recipients.to);- form.setRecipients('cc', restoredSnapshot.recipients.cc);- form.setRecipients('bcc', restoredSnapshot.recipients.bcc);- form.setSubject(restoredSnapshot.subject);- for (const attachment of restoredSnapshot.attachments) {- form.attachments.add(attachment);- }- undoComposeSnapshot = null;- }-- const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();- const saveDraftMutation = useSaveDraftMutation();- const deleteDraftMutation = useDeleteDraftMutation();-- function collectDraft() {- $removeAllWatermarkNodes(editor());- const prepared = prepareEmailBody(editor());- if (!prepared) {- logger.error(- new Error('Unable to prepare email body for draft collection.')- );- return null;- }- if (- !hasDraftContent(- prepared.bodyText,- form.subject(),- form.attachments.list().length,- form.recipients().to.length +- form.recipients().cc.length +- form.recipients().bcc.length- )- ) {- 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 deleteDraftMutation.mutateAsync({ draftId: draftID });- }- setCurrentDraftID(undefined);- return;- }-- const draftResponse = await saveDraftMutation.mutateAsync({- draft: {- ...draftToSave,- db_id: currentDraftID(),- },- });-- const draftId = draftResponse.draft.db_id;- if (draftId) {- // 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: draftId,- 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(draftId);-- return draftId;- }- }-- const scheduleDraftSave = debounce(() => {- void executeSaveDraft();- }, DRAFT_DEBOUNCE_MS);-- const withDraftSave =- <T,>(setter: (v: T) => void) =>- (v: T) => {- setter(v);- scheduleDraftSave();- };-- const onAddAttachments = (attachments: DraftFormAttachment[]) => {- for (const attachment of attachments) {- form.attachments.add(attachment);- }- scheduleDraftSave();- };-- const removeAttachmentMutation = useRemoveDraftAttachmentMutation();- const removeForwardedAttachmentMutation =- useRemoveForwardedAttachmentMutation();-- const handleRemoveAttachment = (attachment: DraftFormAttachment) => {- if (attachment.type === 'local') {- form.attachments.removeByFile(attachment.file);- } else if (attachment.type === 'forwarded') {- form.attachments.removeForwarded(attachment.attachmentID);- } else {- form.attachments.removeByID(attachment.attachmentID);- }-- const savedDraftID = currentDraftID();-- if (!savedDraftID || !attachment.attachmentID) return;-- if (attachment.type === 'forwarded') {- removeForwardedAttachmentMutation.mutate({- draftID: savedDraftID,- attachmentID: attachment.attachmentID,- });- } else {- 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);-- const isCcVisible = () => showCc() || form.recipients().cc.length > 0;- const isBccVisible = () => showBcc() || form.recipients().bcc.length > 0;-- onMount(() => {- const container = refs().containerRef;- if (!container) return;- attachComposeHotkeys(container);- });-- registerHotkey({- hotkey: 'shift+cmd+o',- scopeId: composeHotkeyScope,- description: 'Edit "To" recipients',- keyDownHandler: () => {- refs()?.directRecipientsSelector?.focus();- return true;- },- runWithInputFocused: true,- hotkeyToken: TOKENS.email.compose.edit.recipients,- shouldReturnFocusOnClose: false,- });-- registerHotkey({- hotkey: 'shift+cmd+c',- scopeId: composeHotkeyScope,- description: 'Edit "Cc" recipients',- keyDownHandler: () => {- const visible = showCc();- if (!visible) {- setShowCc(true);- queueMicrotask(() => refs()?.ccRecipientsSelector?.focus());- return true;- }-- refs()?.ccRecipientsSelector?.focus();-- return true;- },- runWithInputFocused: true,- hotkeyToken: TOKENS.email.compose.edit.ccRecipients,- shouldReturnFocusOnClose: false,- });-- registerHotkey({- hotkey: 'shift+cmd+b',- scopeId: composeHotkeyScope,- description: 'Edit "Bcc" recipients',- keyDownHandler: () => {- const visible = showBcc();- if (!visible) {- setShowBcc(true);- queueMicrotask(() => refs()?.bccRecipientsSelector?.focus());- return true;- }-- refs()?.bccRecipientsSelector?.focus();-- return true;- },- runWithInputFocused: true,- hotkeyToken: TOKENS.email.compose.edit.bccRecipients,- shouldReturnFocusOnClose: false,- });-- registerHotkey({- hotkey: 'shift+cmd+s',- scopeId: composeHotkeyScope,- description: 'Edit subject',- keyDownHandler: () => {- refs()?.subjectInput?.focus();- return true;- },- runWithInputFocused: true,- hotkeyToken: TOKENS.email.compose.edit.subject,- shouldReturnFocusOnClose: false,- });-- registerHotkey({- hotkey: 'shift+cmd+m',- scopeId: composeHotkeyScope,- description: 'Edit message',- keyDownHandler: () => {- refs()?.messageInput?.focus();- return true;- },- runWithInputFocused: true,- hotkeyToken: TOKENS.email.compose.edit.message,- shouldReturnFocusOnClose: false,- });-- const previewName = createMemo(() => {- const recipients = form.recipients().to;- if (recipients.length === 0) {- return 'Draft email';- }-- 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();-- const [validationError, setValidationError] =- createSignal<EmailComposeError | null>(null);-- const undoSend = async (draftId: string) => {- try {- await emailClient.unscheduleMessage({ draftID: draftId });- queryClient.invalidateQueries({- queryKey: emailKeys.previews._def,- });- replaceSplit({- content: {- type: 'component',- id: 'email-compose',- params: { draftID: draftId },- },- });- toast.success('Send cancelled');- invalidateSoupEntity(draftId);- } catch {- toast.failure('Failed to undo send');- }- };-- const sendMutation = useSendMessageMutation({- onSuccess: (data) => {- const draftId = data.message.db_id;- const toastId = toast.success(- 'Email sent',- undefined,- draftId- ? [- {- label: 'Undo',- icon: ArrowCounterClockwise,- onClick: () => {- if (toastId != null) toast.dismiss(toastId);- void undoSend(draftId);- },- },- ]- : undefined,- 10_000- );- if (data.message.thread_db_id) {- replaceSplit({- content: { type: 'email', id: data.message.thread_db_id },- mergeHistory: true,- });- }- },- onError: () => {- toast.failure('Failed to send email');- },- });-- const onSubmit = async () => {- setValidationError(null);-- const currentEditor = editor();-- // Snapshot editor state before watermark so undo-send can restore it- if (currentEditor) {- const snapshotHtml = currentEditor.read(() =>- $generateHtmlFromNodes(currentEditor)- );- const draftId = currentDraftID();- if (draftId) {- undoComposeSnapshot = {- draftId,- recipients: structuredClone(unwrap(form.recipients())),- subject: form.subject(),- bodyHtml: snapshotHtml,- attachments: [...form.attachments.list()],- };- }- }-- // 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();-- if (!recipients.to.length) {- setValidationError(- new EmailComposeError(- 'no_recipient',- 'Please select at least one recipient'- )- );- return;- }-- if (!data.raw.trim() && !isMobile()) {- setValidationError(- new EmailComposeError('no_message', 'Please enter a message')- );- return;- }-- if (!form.subject()?.trim() && !isMobile()) {- setValidationError(- new EmailComposeError('no_subject', 'Please enter a subject')- );- return;- }-- if (!currentLink) {- setValidationError(- new EmailComposeError('no_link', 'Unable to find linked email account')- );- return;- }-- // Failsafe: don't send if a scheduled send time is set- if (form.sendTime()) {- return;- }-- sendMutation.mutate({- message: {- to: convertToContactInfoArray(recipients.to),- cc:- recipients.cc.length > 0- ? convertToContactInfoArray(recipients.cc)- : [],- bcc:- recipients.bcc.length > 0- ? convertToContactInfoArray(recipients.bcc)- : [],- subject: form.subject(),- body_text: data.text,- body_html: data.html,- body_macro: data.raw,- db_id: currentDraftID(),- },- });-- cleanupWatermark();- };-- const unscheduleMessageMutation = useUnscheduleMessageMutation({- onSuccess: (_data, vars) => {- toast.success('Email unscheduled');- invalidateSoupEntity(vars.draftID);- },- onError: () => {- toast.failure('Failed to unschedule email');- },- });-- const handleSendTimeChange = async (date: Date | null) => {- const currentSendTime = form.sendTime();- const currentDraft = currentDraftID();-- // If we unset the send time, we need to unschedule the message- if (!date && currentSendTime && currentDraft) {- unscheduleMessageMutation.mutate({- draftID: currentDraft,- });- form.setSendTime(date);- return;- }-- form.setSendTime(date);-- if (date) {- // Ensure draft is saved before scheduling- const draftID = currentDraft ?? (await executeSaveDraft());- if (!draftID) {- toast.failure('Failed to schedule message', 'Draft required');- return;- }-- await emailClient.scheduleMessage({- draftID,- send_time: date.toISOString(),- });-- // Mark the thread as done- const threadID = saveDraftMutation.data?.draft.thread_db_id;- if (threadID) {- await emailClient.flagArchived({ id: threadID, value: true });- }- }- };-- // Unschedule when all recipients are removed- const totalRecipientCount = () => {- const r = form.recipients();- return r.to.length + r.cc.length + r.bcc.length;- };- createEffect(- on(- totalRecipientCount,- (count) => {- if (count === 0 && form.sendTime()) {- handleSendTimeChange(null);- }- },- { defer: true }- )- );-- const resetState = () => {- clearEmailBody(editor());- setContent('');- setCurrentDraftID(undefined);- form.clear();- };-- const deleteDraftAndReset = async () => {- const draftId = currentDraftID();- if (draftId) {- await deleteDraftMutation.mutateAsync({ draftId });- }- resetState();- };-- const withValidationError = (type: EmailComposeErrors) => {- const error = validationError();- if (error?.type === type) return error;- return undefined;- };-- const initialHtml = () => {- if (restoredSnapshot) {- return restoredSnapshot.bodyHtml;- }-- const draft = form.draft;- if (!draft) return;-- if (draft.body_html_sanitized) {- return decodeBase64Utf8(draft.body_html_sanitized);- }-- if (draft.body_text) {- return plainTextToHtml(draft.body_text);- }- };-- const getRecipientOptions = () => {- // If we're being displayed for a draft,- // we should get the recipients from the draft- const fromDraft = emailContext?.recipientOptions();-- return fromDraft ?? destinationOptions();- };-- const [recipientDragState, setRecipientDragState] =- createSignal<DragState | null>(null);-- const handleChipDragStart = (- field: RecipientFieldId,- recipient: EmailRecipient,- e: DragEvent- ) => {- if (!e.dataTransfer) return;- setRecipientDragState({ recipient, sourceField: field });- e.dataTransfer.effectAllowed = 'move';- e.dataTransfer.setData('text/plain', '');- };-- const handleChipDragEnd = () => {- setRecipientDragState(null);- };-- const handleRecipientDrop = (- targetField: RecipientFieldId,- recipient: EmailRecipient,- sourceField: RecipientFieldId- ) => {- // Remove from source- const sourceList = form.recipients()[sourceField];- form.setRecipients(- sourceField,- sourceList.filter((r) => r.id !== recipient.id)- );- // Add to target (avoid duplicates)- const targetList = form.recipients()[targetField];- if (!targetList.some((r) => r.id === recipient.id)) {- form.setRecipients(targetField, [...targetList, recipient]);- }- // Auto-show cc/bcc if dropping into them- if (targetField === 'cc') setShowCc(true);- if (targetField === 'bcc') setShowBcc(true);- scheduleDraftSave();- };-- const isDraftSaving = () => saveDraftMutation.isPending;-- const laggedIsDraftSaving = stickyGate(isDraftSaving, 250);-- return (- <>- <Show when={!isMobile()}>- <SplitHeaderLeft>- <StaticSplitLabel- class="ph-no-capture"- label={form.subject() || previewName()}- iconType={isMobile() ? undefined : 'email'}- badges={- isMobile()- ? []- : [- <SplitHeaderBadge- text="draft"- tooltip="This is a Draft Email"- />,- ]- }- />- </SplitHeaderLeft>- </Show>- <div- ref={registerRef('containerRef')}- class="relative flex flex-col w-full h-full min-h-0 overflow-hidden text-sm"- >- <Show when={hasLinkError()}>- <EmailPermissionsBanner />- </Show>-- <div- ref={mobileScrollRef}- class="macro-message-width sm:macro-message-padding mx-auto w-full max-h-full my-2 sm:my-12 mobile:my-0 px-2 sm:px-4 mobile:px-0 overflow-hidden mobile:overflow-y-auto mobile:hide-scrollbar mobile:min-h-full"- classList={{- 'pointer-events-none opacity-50': hasLinkError(),- }}- >- <WrapUnlessMobile- wrapper={(children) => (- <ClippedPanel tl={!beveledCorners()}>{children}</ClippedPanel>- )}- >- <div- class="w-full p-4 bg-input max-h-full mobile:max-h-none overflow-y-auto flex flex-col min-h-0 mobile:min-h-full"- classList={{- 'pointer-events-none opacity-50': hasLinkError(),- }}- >- <div class="macro-message-width mx-auto pb-1 w-full h-max shrink-0">- <div class="mb-4 h-6 flex items-center justify-between">- <Suspense- fallback={- <div class="flex gap-1 items-center">- <CircleSpinner class="w-4 h-4 animate-spin" />- <span class="text-ink-extra-muted/50 text-xs">- Processing...- </span>- </div>- }- >- <Show when={link()}>- {(link) => (- <div class="text-xs text-ink-extra-muted/50">- from {link().email_address}- </div>- )}- </Show>- </Suspense>- <div class="flex gap-2 ml-auto">- <Show when={!isCcVisible()}>- <button- type="button"- class="text-ink-muted hover:text-ink hover:bg-hover"- onClick={() => setShowCc(true)}- disabled={hasLinkError()}- >- + Cc- </button>- </Show>- <Show when={!isBccVisible()}>- <button- type="button"- class="text-ink-muted hover:text-ink hover:bg-hover"- onClick={() => setShowBcc(true)}- disabled={hasLinkError()}- >- + Bcc- </button>- </Show>- </div>- </div>-- <div class="flex flex-col gap-2">- <ComposeFieldRow- label="To"- fieldId="to"- dragState={recipientDragState}- onRecipientDrop={(recipient, sourceField) =>- handleRecipientDrop('to', recipient, sourceField)- }- >- <RecipientSelector- inputRef={registerRef('directRecipientsSelector')}- options={getRecipientOptions}- selectedOptions={form.recipients().to}- setSelectedOptions={withDraftSave((next) =>- form.setRecipients('to', next)- )}- placeholder="Macro users or email addresses"- focusOnMount={!hasLinkError()}- hideBorder- noBrackets- disabled={hasLinkError()}- onChipDragStart={(option, e) =>- handleChipDragStart('to', option, e)- }- onChipDragEnd={handleChipDragEnd}- />- <Show when={withValidationError('no_recipient')}>- {(err) => (- <div class="text-failure-ink text-sm mt-1">- {err().message}- </div>- )}- </Show>- </ComposeFieldRow>-- <Show when={isCcVisible()}>- <ComposeFieldRow- label="Cc"- fieldId="cc"- dragState={recipientDragState}- onRecipientDrop={(recipient, sourceField) =>- handleRecipientDrop('cc', recipient, sourceField)- }- >- <RecipientSelector- inputRef={registerRef('ccRecipientsSelector')}- options={getRecipientOptions}- selectedOptions={form.recipients().cc}- setSelectedOptions={withDraftSave((next) =>- form.setRecipients('cc', next)- )}- placeholder="Macro users or email addresses"- hideBorder- noBrackets- disabled={hasLinkError()}- onChipDragStart={(option, e) =>- handleChipDragStart('cc', option, e)- }- onChipDragEnd={handleChipDragEnd}- />- </ComposeFieldRow>- </Show>-- <Show when={isBccVisible()}>- <ComposeFieldRow- label="Bcc"- fieldId="bcc"- dragState={recipientDragState}- onRecipientDrop={(recipient, sourceField) =>- handleRecipientDrop('bcc', recipient, sourceField)- }- >- <RecipientSelector- inputRef={registerRef('bccRecipientsSelector')}- options={getRecipientOptions}- selectedOptions={form.recipients().bcc}- setSelectedOptions={withDraftSave((next) =>- form.setRecipients('bcc', next)- )}- placeholder="Macro users or email addresses"- hideBorder- noBrackets- disabled={hasLinkError()}- onChipDragStart={(option, e) =>- handleChipDragStart('bcc', option, e)- }- onChipDragEnd={handleChipDragEnd}- />- </ComposeFieldRow>- </Show>-- <div class="w-full flex items-center gap-2 border-b border-edge-muted focus-within:border-accent py-2">- <div class="shrink-0 text-ink-placeholder/70">Subject</div>-- <div class="flex-1">- <input- ref={registerRef('subjectInput')}- type="text"- value={form.subject()}- placeholder="Subject"- class="w-full resize-none placeholder:text-ink-placeholder p-1 ml-1"- onInput={(e) => {- form.setSubject(e.currentTarget.value);- scheduleDraftSave();- }}- disabled={hasLinkError()}- />- </div>-- <Show when={withValidationError('no_subject')}>- {(err) => (- <div class="text-failure-ink text-sm mt-1">- {err().message}- </div>- )}- </Show>- </div>- </div>- </div>-- <div- class="w-full h-full flex flex-col min-h-0 mt-4"- classList={{- 'pointer-events-none opacity-50': hasLinkError(),- }}- >- <ComposeEmailInput- captureEditor={setEditor}- inputRef={registerRef('messageInput')}- mobileScrollRef={() => mobileScrollRef}- initialHtml={initialHtml()}- onContentChange={onContentChange}- onAddAttachments={onAddAttachments}- onRemoveAttachment={handleRemoveAttachment}- attachments={form.attachments.list()}- sendTime={form.sendTime()}- onSendTimeChange={handleSendTimeChange}- scheduleSendDisabled={- form.recipients().to.length === 0 &&- form.recipients().cc.length === 0 &&- form.recipients().bcc.length === 0- }- onSubmit={() => void onSubmit()}- isSubmitting={sendMutation.isPending}- isDraftSaving={laggedIsDraftSaving()}- hasDraft={currentDraftID() != null}- onDraftDeletePress={deleteDraftAndReset}- disabled={hasLinkError() || sendMutation.isPending}- />- <Show when={withValidationError('no_message')}>- {(err) => (- <div class="text-failure-ink mt-1">{err().message}</div>- )}- </Show>- </div>- </div>- </WrapUnlessMobile>- </div>- </div>- </>- );-}--function convertToContactInfoArray(- recipients: WithCustomUserInput<'user' | 'contact'>[]-): ContactInfo[] {- return recipients.map((recipient) => ({- email: recipient.data.email,- name:- 'name' in recipient.data ? recipient.data.name || undefined : undefined,- }));-}diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsxdeleted file mode 100644index 4039d26977..0000000000--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx+++ /dev/null@@ -1,452 +0,0 @@-import ArrowUp from '@icon/bold/arrow-up-bold.svg';-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';-import { useHasPaidAccess } from '@core/auth';-import { FileDropOverlay } from '@core/component/FileDropOverlay';-import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';-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 Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';-import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';-import PaperclipHorizontalIcon from '@phosphor-icons/core/regular/paperclip-horizontal.svg?component-solid';-import { useUserId } from '@core/context/user';-import { defaultSelectionData } from 'core/component/LexicalMarkdown/plugins';-import {- NODE_TRANSFORM,- type NodeTransformType,-} from 'core/component/LexicalMarkdown/plugins/node-transform/nodeTransformPlugin';-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';-import {- FORMAT_TEXT_COMMAND,- type LexicalEditor,- type TextFormatType,-} from 'lexical';-import PaperPlane from '@macro-icons/wide/paper-plane-cutout.svg';-import {- type Accessor,- createSignal,- For,- Match,- onMount,- Show,- Switch,-} from 'solid-js';-import { type FocusableElement, tabbable } from 'tabbable';-import { makeAttachmentPublic } from '../util/makeAttachmentPublic';-import { Button } from '@ui/components/Button';-import { fileSelector } from '@core/directive/fileSelector';-import { toast } from '@core/component/Toast/Toast';-import { Tooltip } from '@core/component/Tooltip';-import { plural } from '@core/util/string';-import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';-import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';-import { EmailDateSelector } from '@block-email/component/email-date-selector';-import { ENABLE_EMAIL_SCHEDULED_SEND } from '@core/constant/featureFlags';-import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHeader';-import { isMobile } from '@core/mobile/isMobile';--false && fileFolderDrop;--type ComposeEmailInputProps = {- inputRef?: (el: HTMLDivElement) => void;- captureEditor?: (editor: LexicalEditor) => void;- onSubmit: () => void;- disabled?: boolean;- isSubmitting?: boolean;- hasDraft?: boolean;- onDraftDeletePress?: VoidFunction;- isDraftSaving?: boolean;- attachments?: DraftFormAttachment[];- initialHtml?: string;- onAddAttachments?: (attachments: DraftFormAttachment[]) => void;- onRemoveAttachment?: (attachment: DraftFormAttachment) => void;- onContentChange?: (content: string) => void;- sendTime?: Date | null;- onSendTimeChange?: (date: Date | null) => void;- scheduleSendDisabled?: boolean;- mobileScrollRef?: Accessor<HTMLElement | undefined>;-};--export function ComposeEmailInput(props: ComposeEmailInputProps) {- const hasPaidAccess = useHasPaidAccess();-- const [editor, setEditor] = createSignal<LexicalEditor>();-- const [isDragging, setIsDragging] = createSignal<boolean>();-- const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(false);-- const panel = useSplitPanel();-- const focusSibling = (direction: 'next' | 'prev') => {- const panelRef = panel?.panelRef();- if (!panelRef) return;- const tabbableEls = tabbable(panelRef);- const activeEl = document.activeElement;- const activeElIndex = tabbableEls.indexOf(activeEl as FocusableElement);- if (activeElIndex > -1) {- const ndx = activeElIndex + (direction === 'next' ? 1 : -1);- if (ndx < 0 || ndx >= tabbableEls.length) return false;- const prevEl = tabbableEls[ndx];- if (!prevEl) return false;- prevEl.focus();- return true;- } else {- tabbableEls.at(-1)?.focus();- return true;- }- };-- useUserId();-- let bodyDiv!: HTMLDivElement;- let attachButtonRef!: HTMLDivElement;-- // Set up hotkey scope for the compose message component- const [attachComposeHotkeys, composeHotkeyScope] =- useHotkeyDOMScope('compose-message');- const [composeContainerRef, setComposeContainerRef] = createSignal<- HTMLElement | undefined- >();-- function handleSend() {- props.onSubmit();- }-- onMount(() => {- const container = composeContainerRef();- if (!container) return;- attachComposeHotkeys(container);- });-- const onAddFilesAndDirs = (- files: FileSystemFileEntry[],- directories: FileSystemDirectoryEntry[]- ) => {- const editor_ = editor();- if (!editor_) return;-- handleFileFolderDrop(- files,- directories,- createFilesReadyHandler(- editor_,- undefined,- undefined,- undefined,- (uploadedItemIds) => {- uploadedItemIds.forEach((itemId) => {- makeAttachmentPublic(itemId);- });- },- { width: 542, height: 542 }- )- );- };-- registerHotkey({- hotkey: 'cmd+enter',- scopeId: composeHotkeyScope,- description: 'Send email',- keyDownHandler: () => {- if (props.sendTime) return false;- handleSend();- return true;- },- runWithInputFocused: true,- hotkeyToken: 'email.send',- 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,- }))- );- };-- const captureEditor = (editor: LexicalEditor) => {- setEditor(editor);- props.captureEditor?.(editor);- };-- return (- <div- ref={setComposeContainerRef}- class="relative flex flex-col flex-1 items-center justify-between min-h-0"- >- <div class="w-full h-full min-h-60 sm:max-h-full mobile:flex-1 flex flex-col">- <Show when={showFormatRibbon()}>- <FormatRibbon- class="-ml-3"- state={structuredClone(defaultSelectionData)}- inlineFormat={(format: TextFormatType) => {- editor()?.dispatchCommand(FORMAT_TEXT_COMMAND, format);- }}- nodeFormat={(transform: NodeTransformType) => {- editor()?.dispatchCommand(NODE_TRANSFORM, transform);- }}- />- </Show>-- <div- class="grow w-full h-full flex flex-col cursor-text placeholder:text-ink-placeholder placeholder:opacity-50 overflow-auto"- ref={bodyDiv}- onclick={() => {- editor()?.focus();- }}- use:fileFolderDrop={{- onDragStart: (valid) => setIsDragging(valid),- onDragEnd: () => setIsDragging(false),- onDrop: (files, dirs) => {- handleFileFolderDrop(files, dirs, (u) =>- handleAddAttachments(u.map((f) => f.file))- );- },- }}- >- <div class={`${!isDragging() && 'hidden'} absolute inset-0`}>- <FileDropOverlay>Drop file(s) to attach</FileDropOverlay>- </div>- <MarkdownTextarea- domRef={props.inputRef}- captureEditor={captureEditor}- scrollRef={props.mobileScrollRef}- initialHtml={props.initialHtml}- class="text-sm break-words text-ink mobile:overflow-auto h-auto"- editable={() => !props.disabled}- placeholder="Use `@` to reference files"- watermark={!hasPaidAccess() ? <MacroSignatureButton /> : undefined}- onChange={props.onContentChange}- onFocusLeaveStart={(e) => {- e.preventDefault();- focusSibling('prev');- }}- onFocusLeaveEnd={(e) => {- e.preventDefault();- focusSibling('next');- }}- portalScope="local"- 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>- <Match when={attachment.type === 'forwarded' && attachment}>- {(attachment) => (- <EmailAttachmentPill- attachment={{- fileName: attachment().fileName,- mimeType: attachment().mimeType,- }}- 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">- <Show- when={!isMobile()}- fallback={- <SplitHeaderRight>- <div class="flex items-center pl-2">- <Show when={props.hasDraft}>- <Button- onclick={props.onDraftDeletePress}- tooltip="Delete draft"- class="aspect-square p-1"- disabled={props.disabled}- >- <Trash />- </Button>- </Show>- <div class="relative" ref={attachButtonRef}>- <Button- ref={(el) =>- fileSelector(el, () => ({- multiple: true,- onSelect: handleAddAttachments,- }))- }- tooltip="Attach"- class="aspect-square p-1"- disabled={props.disabled}- >- <PaperclipHorizontalIcon class="h-5" />- </Button>- </div>- <Show when={ENABLE_EMAIL_SCHEDULED_SEND}>- <EmailDateSelector- sendTime={props.sendTime}- onSendTimeChange={props.onSendTimeChange}- disabled={props.scheduleSendDisabled}- compact- />- </Show>- <Tooltip- tooltip={- props.sendTime ? 'Send time is scheduled' : undefined- }- >- <Button- class="ml-8"- disabled={- props.isSubmitting || props.disabled || !!props.sendTime- }- onClick={() => {- handleSend();- }}- >- <PaperPlane class="size-4.5 text-accent" />- </Button>- </Tooltip>- </div>- </SplitHeaderRight>- }- >- <div class="flex flex-row items-center gap-2">- <div class="relative" ref={attachButtonRef}>- <Button- ref={(el) =>- fileSelector(el, () => ({- multiple: true,- onSelect: handleAddAttachments,- }))- }- tooltip="Attach"- class="aspect-square p-1"- disabled={props.disabled}- >- <PaperclipIcon class="h-5" />- </Button>- </div>- <Button- variant="ghost"- size="icon-sm"- disabled={props.disabled}- onClick={() => {- setShowFormatRibbon(!showFormatRibbon());- }}- >- <TextAa />- </Button>- <Show when={ENABLE_EMAIL_SCHEDULED_SEND}>- <EmailDateSelector- sendTime={props.sendTime}- onSendTimeChange={props.onSendTimeChange}- disabled={props.scheduleSendDisabled}- />- </Show>- <Show when={props.hasDraft && !props.isDraftSaving}>- <Button- onclick={props.onDraftDeletePress}- tooltip="Delete draft"- class="aspect-square *:h-5 p-1"- >- <Trash />- </Button>- </Show>- <Show when={props.isDraftSaving}>- <div class="aspect-square p-1 flex items-center justify-center">- <Spinner class="size-5 animate-spin text-ink-muted" />- </div>- </Show>- </div>-- <Tooltip- tooltip={props.sendTime ? 'Send time is scheduled' : undefined}- >- <button- disabled={- props.isSubmitting || props.disabled || !!props.sendTime- }- onClick={() => {- handleSend();- }}- 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={!props.isSubmitting}- 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">- <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />- </div>- </Show>- </button>- </Tooltip>- </Show>- </div>- </div>- );-}diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsxindex dfac437ce6..e7b6398139 100644--- a/js/app/packages/block-email/component/Email.tsx+++ b/js/app/packages/block-email/component/Email.tsx@@ -1,17 +1,21 @@+import { EmailCompose } from '@block-email/component/compose/Compose';import {EmailProvider,useEmailContext,} from '@block-email/component/EmailContext';+import { EmailInput } from '@block-email/component/EmailInput';import { CustomScrollbar } from '@core/component/CustomScrollbar';+import { FloatingInputLoader } from '@core/component/FloatingInputLoader';+import { useUserContext } from '@core/context/user';import { TOKENS } from '@core/hotkey/tokens';import { registerScopeSignalHotkey } from '@core/hotkey/utils';+import { isMobile } from '@core/mobile/isMobile';import {blockElementSignal,blockHotkeyScopeSignal,} from '@core/signal/blockElement';import type { ApiMessage } from '@service-email/generated/schemas';import { createCallback } from '@solid-primitives/rootless';-import { useUserContext } from '@core/context/user';import {type Accessor,createEffect,@@ -23,7 +27,6 @@ import {Switch,untrack,} from 'solid-js';-import { isMobile } from '@core/mobile/isMobile';import { isScrollingToMessage } from '../signal/scrollState';import { registerEmailHotkeys } from '../util/emailHotkeys';import { scrollToMessage } from '../util/scrollToMessage';@@ -31,9 +34,6 @@ import { EmailFormContextProvider } from './EmailFormContext';import { MessageList } from './MessageList';import { ModalsProvider } from './ModalsProvider';import { TopBar } from './TopBar';-import { EmailCompose } from '@block-email/component/Compose';-import { EmailInput } from '@block-email/component/EmailInput';-import { FloatingInputLoader } from '@core/component/FloatingInputLoader';const TARGET_MESSAGE_HIGHLIGHT_MS = 800;const SCROLL_ANIMATION_MS = 1000;@@ -209,7 +209,9 @@ function EmailContent(props: EmailViewProps) {// Check if there is an unread messageif (lastUnreadMessageId_) {setTimeout(() =>- performScrollToMessage(lastUnreadMessageId_!, { behavior: 'instant' })+ performScrollToMessage(lastUnreadMessageId_!, {+ behavior: 'instant',+ }));context.messages.setFocused(lastUnreadMessageId_!);} else {diff --git a/js/app/packages/block-email/component/compose/Compose.tsx b/js/app/packages/block-email/component/compose/Compose.tsxnew file mode 100644index 0000000000..4253273429--- /dev/null+++ b/js/app/packages/block-email/component/compose/Compose.tsx@@ -0,0 +1,652 @@+import { useSplitLayout } from '@app/component/split-layout/layout';+import type { EmailFormRecipients } from '@block-email/component/createEmailFormState';+import {+ createEmailFormState,+ type DraftFormAttachment,+} from '@block-email/component/createEmailFormState';+import { useMaybeEmailContext } from '@block-email/component/EmailContext';+import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';+import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';+import { plainTextToHtml } from '@block-email/util/plainTextToHtml';+import {+ clearEmailBody,+ hasDraftContent,+ prepareEmailBody,+} from '@block-email/util/prepareEmailBody';+import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';+import { useHasPaidAccess } from '@core/auth';+import { toast } from '@core/component/Toast/Toast';+import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';+import {+ type ContactInfo,+ tryMacroId,+ useDisplayName,+ type WithCustomUserInput,+} from '@core/user';+import { stickyGate } from '@core/util/debounce';+import { $generateHtmlFromNodes } from '@lexical/html';+import {+ $appendWatermarkNodeToLast,+ $removeAllWatermarkNodes,+} from '@lexical-core';+import { logger } from '@observability/logger';+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';+import { queryClient } from '@queries/client';+import {+ useRemoveDraftAttachmentMutation,+ useRemoveForwardedAttachmentMutation,+ useUploadDraftAttachmentsMutation,+} from '@queries/email/attachment';+import {+ useDeleteDraftMutation,+ useSaveDraftMutation,+} from '@queries/email/draft';+import { emailKeys } from '@queries/email/keys';+import { useEmailLinksQuery } from '@queries/email/link';+import {+ useSendMessageMutation,+ useUnscheduleMessageMutation,+} from '@queries/email/thread';+import { invalidateSoupEntity } from '@queries/soup/cache';+import { emailClient } from '@service-email/client';+import { debounce } from '@solid-primitives/scheduled';+import type { LexicalEditor } from 'lexical';+import { createEffect, createMemo, createSignal, on } from 'solid-js';+import { unwrap } from 'solid-js/store';+import {+ type ComposeContextValue,+ ComposeProvider,+ type ComposeValidationError,+} from './ComposeContext';+import { ComposeLayout } from './ComposeLayout';+import { EmailComposeToolbar } from './ComposeToolbar';++const DRAFT_DEBOUNCE_MS = 1000;++type UndoComposeSnapshot = {+ draftId: string;+ recipients: EmailFormRecipients;+ subject: string;+ bodyHtml: string;+ attachments: DraftFormAttachment[];+};++let undoComposeSnapshot: UndoComposeSnapshot | null = null;++type EmailComposeProps = {+ draftID?: string;+};++export function EmailCompose(props: EmailComposeProps) {+ const hasPaidAccess = useHasPaidAccess();+ const emailLinksQuery = useEmailLinksQuery();+ const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();+ const saveDraftMutation = useSaveDraftMutation();+ const deleteDraftMutation = useDeleteDraftMutation();+ const emailContext = useMaybeEmailContext();++ const link = createMemo(() => {+ const data = emailLinksQuery.data;+ if (data && data.links.length > 0) {+ return data.links[0];+ }+ return undefined;+ });++ const hasLinkError = createMemo(() => {+ if (emailLinksQuery.isPending) return false;+ return (+ emailLinksQuery.isError ||+ (emailLinksQuery.data && emailLinksQuery.data.links.length === 0)+ );+ });++ const { users: destinationOptions } = useCombinedRecipients();++ 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>(+ props.draftID+ );++ // Restore form state from undo-send snapshot if available+ const restoredSnapshot =+ undoComposeSnapshot?.draftId === props.draftID ? undoComposeSnapshot : null;++ if (restoredSnapshot) {+ form.setRecipients('to', restoredSnapshot.recipients.to);+ form.setRecipients('cc', restoredSnapshot.recipients.cc);+ form.setRecipients('bcc', restoredSnapshot.recipients.bcc);+ form.setSubject(restoredSnapshot.subject);+ for (const attachment of restoredSnapshot.attachments) {+ form.attachments.add(attachment);+ }+ undoComposeSnapshot = null;+ }++ // --- Draft persistence ---++ function collectDraft() {+ $removeAllWatermarkNodes(editor());+ const prepared = prepareEmailBody(editor());+ if (!prepared) {+ logger.error(+ new Error('Unable to prepare email body for draft collection.')+ );+ return null;+ }+ if (+ !hasDraftContent(+ prepared.bodyText,+ form.subject(),+ form.attachments.list().length,+ form.recipients().to.length ++ form.recipients().cc.length ++ form.recipients().bcc.length+ )+ ) {+ return null;+ }+ 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 deleteDraftMutation.mutateAsync({ draftId: draftID });+ }+ setCurrentDraftID(undefined);+ return;+ }++ const draftResponse = await saveDraftMutation.mutateAsync({+ draft: {+ ...draftToSave,+ db_id: currentDraftID(),+ },+ });++ const draftId = draftResponse.draft.db_id;+ if (draftId) {+ 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: draftId,+ attachments: attachments.map((a) => a.file),+ });++ for (const attachment of uploaded.attachments) {+ form.attachments.assignAttachmentID(+ attachment.file,+ attachment.attachmentID+ );+ }+ }++ setCurrentDraftID(draftId);+ return draftId;+ }+ }++ const scheduleDraftSave = debounce(() => {+ void executeSaveDraft();+ }, DRAFT_DEBOUNCE_MS);++ // --- Attachment handling ---++ const removeAttachmentMutation = useRemoveDraftAttachmentMutation();+ const removeForwardedAttachmentMutation =+ useRemoveForwardedAttachmentMutation();++ const handleAddAttachments = (attachments: DraftFormAttachment[]) => {+ for (const attachment of attachments) {+ form.attachments.add(attachment);+ }+ scheduleDraftSave();+ };++ const handleRemoveAttachment = (attachment: DraftFormAttachment) => {+ if (attachment.type === 'local') {+ form.attachments.removeByFile(attachment.file);+ } else if (attachment.type === 'forwarded') {+ form.attachments.removeForwarded(attachment.attachmentID);+ } else {+ form.attachments.removeByID(attachment.attachmentID);+ }++ const savedDraftID = currentDraftID();+ if (!savedDraftID || !attachment.attachmentID) return;++ if (attachment.type === 'forwarded') {+ removeForwardedAttachmentMutation.mutate({+ draftID: savedDraftID,+ attachmentID: attachment.attachmentID,+ });+ } else {+ removeAttachmentMutation.mutate({+ draftID: savedDraftID,+ attachmentID: attachment.attachmentID,+ });+ }+ };++ // --- Content change ---++ let firstChangeConsumed = false;+ const onContentChange = (newContent: string) => {+ setContent(newContent);+ if (!firstChangeConsumed) {+ firstChangeConsumed = true;+ return;+ }+ scheduleDraftSave();+ };++ // --- Send ---++ const { replaceSplit } = useSplitLayout();++ const [validationError, setValidationError] =+ createSignal<ComposeValidationError | null>(null);++ const undoSend = async (draftId: string) => {+ try {+ await emailClient.unscheduleMessage({ draftID: draftId });+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ replaceSplit({+ content: {+ type: 'component',+ id: 'email-compose',+ params: { draftID: draftId },+ },+ });+ toast.success('Send cancelled');+ invalidateSoupEntity(draftId);+ } catch {+ toast.failure('Failed to undo send');+ }+ };++ const sendMutation = useSendMessageMutation({+ onSuccess: (data) => {+ const draftId = data.message.db_id;+ const toastId = toast.success(+ 'Email sent',+ undefined,+ draftId+ ? [+ {+ label: 'Undo',+ icon: ArrowCounterClockwise,+ onClick: () => {+ if (toastId != null) toast.dismiss(toastId);+ void undoSend(draftId);+ },+ },+ ]+ : undefined,+ 10_000+ );+ if (data.message.thread_db_id) {+ replaceSplit({+ content: { type: 'email', id: data.message.thread_db_id },+ mergeHistory: true,+ });+ }+ },+ onError: () => {+ toast.failure('Failed to send email');+ },+ });++ const onSubmit = async () => {+ setValidationError(null);++ const currentEditor = editor();++ // Snapshot editor state before watermark so undo-send can restore it+ if (currentEditor) {+ const snapshotHtml = currentEditor.read(() =>+ $generateHtmlFromNodes(currentEditor)+ );+ const draftId = currentDraftID();+ if (draftId) {+ undoComposeSnapshot = {+ draftId,+ recipients: structuredClone(unwrap(form.recipients())),+ subject: form.subject(),+ bodyHtml: snapshotHtml,+ attachments: [...form.attachments.list()],+ };+ }+ }++ 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();++ if (!recipients.to.length) {+ setValidationError({+ type: 'no_recipient',+ message: 'Please select at least one recipient',+ });+ return;+ }++ if (!data.raw.trim()) {+ setValidationError({+ type: 'no_message',+ message: 'Please enter a message',+ });+ return;+ }++ if (!form.subject()?.trim()) {+ setValidationError({+ type: 'no_subject',+ message: 'Please enter a subject',+ });+ return;+ }++ if (!currentLink) {+ setValidationError({+ type: 'no_link',+ message: 'Unable to find linked email account',+ });+ return;+ }++ // Failsafe: don't send if a scheduled send time is set+ if (form.sendTime()) {+ return;+ }++ sendMutation.mutate({+ message: {+ to: convertToContactInfoArray(recipients.to),+ cc:+ recipients.cc.length > 0+ ? convertToContactInfoArray(recipients.cc)+ : [],+ bcc:+ recipients.bcc.length > 0+ ? convertToContactInfoArray(recipients.bcc)+ : [],+ subject: form.subject(),+ body_text: data.text,+ body_html: data.html,+ body_macro: data.raw,+ db_id: currentDraftID(),+ },+ });++ cleanupWatermark();+ };++ // --- Schedule ---++ const unscheduleMessageMutation = useUnscheduleMessageMutation({+ onSuccess: (_data, vars) => {+ toast.success('Email unscheduled');+ invalidateSoupEntity(vars.draftID);+ },+ onError: () => {+ toast.failure('Failed to unschedule email');+ },+ });++ const handleSendTimeChange = async (date: Date | null) => {+ const currentSendTime = form.sendTime();+ const currentDraft = currentDraftID();++ if (!date && currentSendTime && currentDraft) {+ unscheduleMessageMutation.mutate({+ draftID: currentDraft,+ });+ form.setSendTime(date);+ return;+ }++ form.setSendTime(date);++ if (date) {+ const draftID = currentDraft ?? (await executeSaveDraft());+ if (!draftID) {+ toast.failure('Failed to schedule message', 'Draft required');+ return;+ }++ await emailClient.scheduleMessage({+ draftID,+ send_time: date.toISOString(),+ });++ const threadID = saveDraftMutation.data?.draft.thread_db_id;+ if (threadID) {+ await emailClient.flagArchived({ id: threadID, value: true });+ }+ }+ };++ // Unschedule when all recipients are removed+ const totalRecipientCount = () => {+ const r = form.recipients();+ return r.to.length + r.cc.length + r.bcc.length;+ };+ createEffect(+ on(+ totalRecipientCount,+ (count) => {+ if (count === 0 && form.sendTime()) {+ handleSendTimeChange(null);+ }+ },+ { defer: true }+ )+ );++ // --- Reset / delete ---++ const resetState = () => {+ clearEmailBody(editor());+ setContent('');+ setCurrentDraftID(undefined);+ form.clear();+ };++ const deleteDraftAndReset = async () => {+ const draftId = currentDraftID();+ if (draftId) {+ await deleteDraftMutation.mutateAsync({ draftId });+ }+ resetState();+ };++ // --- Derived state ---++ const initialHtml = () => {+ if (restoredSnapshot) {+ return restoredSnapshot.bodyHtml;+ }++ const draft = form.draft;+ if (!draft) return;++ if (draft.body_html_sanitized) {+ return decodeBase64Utf8(draft.body_html_sanitized);+ }++ if (draft.body_text) {+ return plainTextToHtml(draft.body_text);+ }+ };++ const getRecipientOptions = () => {+ const fromDraft = emailContext?.recipientOptions();+ return fromDraft ?? destinationOptions();+ };++ const previewName = createMemo(() => {+ const recipients = form.recipients().to;+ if (recipients.length === 0) {+ return 'Draft email';+ }++ 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 isDraftSaving = () => saveDraftMutation.isPending;+ const laggedIsDraftSaving = stickyGate(isDraftSaving, 250);++ // --- Context value ---++ const ctxValue: ComposeContextValue = {+ // Form state (read)+ recipients: form.recipients,+ subject: form.subject,+ attachments: form.attachments.list,+ sendTime: form.sendTime,+ initialHtml,++ // Form state (write)+ setRecipients: (field, value) => {+ form.setRecipients(field, value);+ scheduleDraftSave();+ },+ setSubject: (value) => {+ form.setSubject(value);+ scheduleDraftSave();+ },+ onContentChange,+ onAddAttachments: handleAddAttachments,+ onRemoveAttachment: handleRemoveAttachment,++ // Editor+ captureEditor: setEditor,++ // Actions+ onSend: () => void onSubmit(),+ onDelete: () => void deleteDraftAndReset(),+ onSendTimeChange: handleSendTimeChange,++ // Status+ disabled: () => hasLinkError() || sendMutation.isPending,+ isSending: () => sendMutation.isPending,+ isDraftSaving: () => laggedIsDraftSaving(),+ hasDraft: () => currentDraftID() != null,++ // Validation+ validationError: (type) => {+ const error = validationError();+ if (error?.type === type) return error;+ return undefined;+ },++ // Recipients+ recipientOptions: getRecipientOptions,+ focusRecipientsOnMount: !hasLinkError(),++ // Schedule send+ scheduleSendDisabled: () => totalRecipientCount() === 0,++ // Display+ fromAddress: () => link()?.email_address,+ hasPaidAccess,+ };++ return (+ <ComposeProvider value={ctxValue}>+ <ComposeLayout+ toolbar={<EmailComposeToolbar editor={editor} />}+ hasLinkError={hasLinkError}+ previewName={previewName}+ />+ </ComposeProvider>+ );+}++function convertToContactInfoArray(+ recipients: WithCustomUserInput<'user' | 'contact'>[]+): ContactInfo[] {+ return recipients.map((recipient) => ({+ email: recipient.data.email,+ name:+ 'name' in recipient.data ? recipient.data.name || undefined : undefined,+ }));+}diff --git a/js/app/packages/block-email/component/compose/ComposeBody.tsx b/js/app/packages/block-email/component/compose/ComposeBody.tsxnew file mode 100644index 0000000000..b72b60ac85--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeBody.tsx@@ -0,0 +1,194 @@+import { useSplitPanel } from '@app/component/split-layout/layoutUtils';+import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';+import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';+import { FileDropOverlay } from '@core/component/FileDropOverlay';+import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';+import { createFilesReadyHandler } from '@core/component/LexicalMarkdown/utils/fileUploadUtils';+import { fileFolderDrop } from '@core/directive/fileFolderDrop';+import { handleFileFolderDrop } from '@core/util/upload';+import { cn } from '@ui/utils/classname';+import type { LexicalEditor } from 'lexical';+import {+ type Accessor,+ createSignal,+ For,+ Match,+ Show,+ Switch,+} from 'solid-js';+import type { FocusableElement } from 'tabbable';+import { tabbable } from 'tabbable';+import { makeAttachmentPublic } from '../../util/makeAttachmentPublic';+import { useCompose } from './ComposeContext';++false && fileFolderDrop;++export function ComposeBody(props: {+ inputRef?: (el: HTMLDivElement) => void;+ mobileScrollRef?: Accessor<HTMLElement | undefined>;+ onAddFiles?: (files: File[]) => void;+}) {+ const ctx = useCompose();+ const panel = useSplitPanel();++ const [editor, setEditor] = createSignal<LexicalEditor>();+ const [isDragging, setIsDragging] = createSignal<boolean>();++ const focusSibling = (direction: 'next' | 'prev') => {+ const panelRef = panel?.panelRef();+ if (!panelRef) return;+ const tabbableEls = tabbable(panelRef);+ const activeEl = document.activeElement;+ const activeElIndex = tabbableEls.indexOf(activeEl as FocusableElement);+ if (activeElIndex > -1) {+ const ndx = activeElIndex + (direction === 'next' ? 1 : -1);+ if (ndx < 0 || ndx >= tabbableEls.length) return false;+ const prevEl = tabbableEls[ndx];+ if (!prevEl) return false;+ prevEl.focus();+ return true;+ }+ tabbableEls.at(-1)?.focus();+ return true;+ };++ const onAddFilesAndDirs = (+ files: FileSystemFileEntry[],+ directories: FileSystemDirectoryEntry[]+ ) => {+ const editor_ = editor();+ if (!editor_) return;++ handleFileFolderDrop(+ files,+ directories,+ createFilesReadyHandler(+ editor_,+ undefined,+ undefined,+ undefined,+ (uploadedItemIds) => {+ uploadedItemIds.forEach((itemId) => {+ makeAttachmentPublic(itemId);+ });+ },+ { width: 542, height: 542 }+ )+ );+ };++ let bodyDiv!: HTMLDivElement;++ const captureEditor = (ed: LexicalEditor) => {+ setEditor(ed);+ ctx.captureEditor(ed);+ };++ return (+ <>+ <div class="w-full h-full min-h-60 sm:max-h-full mobile:flex-1 flex flex-col">+ <div+ class="grow w-full h-full flex flex-col cursor-text placeholder:text-ink-placeholder placeholder:opacity-50 overflow-auto"+ ref={bodyDiv}+ onclick={() => {+ editor()?.focus();+ }}+ use:fileFolderDrop={{+ onDragStart: (valid) => setIsDragging(valid),+ onDragEnd: () => setIsDragging(false),+ onDrop: (files, dirs) => {+ handleFileFolderDrop(files, dirs, (u) =>+ props.onAddFiles?.(u.map((f) => f.file))+ );+ },+ }}+ >+ <div class={cn('absolute inset-0', !isDragging() && 'hidden')}>+ <FileDropOverlay>Drop file(s) to attach</FileDropOverlay>+ </div>+ <MarkdownTextarea+ domRef={props.inputRef}+ captureEditor={captureEditor}+ scrollRef={props.mobileScrollRef}+ initialHtml={ctx.initialHtml()}+ class="text-sm break-words text-ink mobile:overflow-auto h-auto"+ editable={() => !ctx.disabled()}+ placeholder="Use `@` to reference files"+ watermark={+ !ctx.hasPaidAccess() ? <MacroSignatureButton /> : undefined+ }+ onChange={ctx.onContentChange}+ onFocusLeaveStart={(e) => {+ e.preventDefault();+ focusSibling('prev');+ }}+ onFocusLeaveEnd={(e) => {+ e.preventDefault();+ focusSibling('next');+ }}+ portalScope="local"+ onPasteFilesAndDirs={onAddFilesAndDirs}+ />+ </div>+ <div class="flex flex-wrap items-center gap-2">+ <For each={ctx.attachments()}>+ {(attachment) => <AttachmentItem attachment={attachment} />}+ </For>+ </div>+ </div>+ <Show when={ctx.validationError('no_message')}>+ {(err) => <div class="text-failure-ink mt-1">{err().message}</div>}+ </Show>+ </>+ );+}++function AttachmentItem(props: { attachment: DraftFormAttachment }) {+ const ctx = useCompose();++ const handleRemove = () => {+ ctx.onRemoveAttachment(props.attachment);+ };++ return (+ <Switch>+ <Match when={props.attachment.type === 'local' && props.attachment}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment().file.name,+ mimeType: attachment().file.type,+ }}+ removable+ onRemove={handleRemove}+ />+ )}+ </Match>+ <Match when={props.attachment.type === 'remote' && props.attachment}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment().fileName,+ mimeType: attachment().contentType,+ }}+ removable+ onRemove={handleRemove}+ />+ )}+ </Match>+ <Match when={props.attachment.type === 'forwarded' && props.attachment}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment().fileName,+ mimeType: attachment().mimeType,+ }}+ removable+ onRemove={handleRemove}+ />+ )}+ </Match>+ </Switch>+ );+}diff --git a/js/app/packages/block-email/component/compose/ComposeContext.ts b/js/app/packages/block-email/component/compose/ComposeContext.tsnew file mode 100644index 0000000000..d5afd93c69--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeContext.ts@@ -0,0 +1,81 @@+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';+import type { EmailRecipient } from '@block-email/component/EmailContext';+import type { LexicalEditor } from 'lexical';+import { type Accessor, createContext, type JSX, useContext } from 'solid-js';++export type EmailFormRecipients = {+ to: EmailRecipient[];+ cc: EmailRecipient[];+ bcc: EmailRecipient[];+};++export type RecipientFieldId = 'to' | 'cc' | 'bcc';++export type ComposeValidationError = {+ type: 'no_recipient' | 'no_message' | 'no_subject' | 'no_link';+ message: string;+};++export interface ComposeContextValue {+ // Form state (read)+ recipients: () => EmailFormRecipients;+ subject: () => string;+ attachments: () => DraftFormAttachment[];+ sendTime: () => Date | null | undefined;+ initialHtml: () => string | undefined;++ // Form state (write)+ setRecipients: (+ field: keyof EmailFormRecipients,+ value: EmailRecipient[]+ ) => void;+ setSubject: (value: string) => void;+ onContentChange: (content: string) => void;+ onAddAttachments: (attachments: DraftFormAttachment[]) => void;+ onRemoveAttachment: (attachment: DraftFormAttachment) => void;++ // Editor+ captureEditor: (editor: LexicalEditor) => void;++ // Actions+ onSend: () => void;+ onDelete?: () => void;+ onSendTimeChange?: (date: Date | null) => void;++ // Status+ disabled: Accessor<boolean>;+ isSending: Accessor<boolean>;+ isDraftSaving: Accessor<boolean>;+ hasDraft: Accessor<boolean>;++ // Validation+ validationError: (+ type: ComposeValidationError['type']+ ) => ComposeValidationError | undefined;++ // Recipients config+ recipientOptions: () => Array<EmailRecipient>;+ focusRecipientsOnMount: boolean;++ // Schedule send+ scheduleSendDisabled?: Accessor<boolean>;++ // Display+ fromAddress?: Accessor<string | undefined>;+ hasPaidAccess: Accessor<boolean>;++ // Toolbar slot — allows orchestrators to provide a custom toolbar+ toolbar?: () => JSX.Element;+}++const ComposeContext = createContext<ComposeContextValue>();++export const ComposeProvider = ComposeContext.Provider;++export function useCompose(): ComposeContextValue {+ const ctx = useContext(ComposeContext);+ if (!ctx) {+ throw new Error('useCompose must be used within a ComposeProvider');+ }+ return ctx;+}diff --git a/js/app/packages/block-email/component/compose/ComposeLayout.tsx b/js/app/packages/block-email/component/compose/ComposeLayout.tsxnew file mode 100644index 0000000000..a20eb1da79--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeLayout.tsx@@ -0,0 +1,289 @@+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';+import {+ SplitHeaderBadge,+ StaticSplitLabel,+} from '@app/component/split-layout/components/SplitLabel';+import { ClippedPanel } from '@core/component/ClippedPanel';+import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';+import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import { isMobile } from '@core/mobile/isMobile';+import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';+import { beveledCorners } from 'core/signal/beveledCorners';+import { createSignal, type JSX, onMount, Show, Suspense } from 'solid-js';+import { CircleSpinner } from '@core/component/CircleSpinner';+import { useCompose } from './ComposeContext';+import { ComposeRecipients } from './ComposeRecipients';+import { ComposeSubject } from './ComposeSubject';+import { ComposeBody } from './ComposeBody';++type ComposeLayoutRefs = {+ directRecipientsSelector: HTMLElement | undefined;+ ccRecipientsSelector: HTMLElement | undefined;+ bccRecipientsSelector: HTMLElement | undefined;+ containerRef: HTMLElement | undefined;+ subjectInput: HTMLElement | undefined;+ messageInput: HTMLElement | undefined;+};++export function ComposeLayout(props: {+ toolbar?: JSX.Element;+ header?: JSX.Element;+ hasLinkError?: () => boolean;+ previewName?: () => string;+}) {+ const ctx = useCompose();++ const hasLinkError = props.hasLinkError ?? (() => false);++ const [refs, setRefs] = createSignal<ComposeLayoutRefs>({+ directRecipientsSelector: undefined,+ ccRecipientsSelector: undefined,+ bccRecipientsSelector: undefined,+ containerRef: undefined,+ subjectInput: undefined,+ messageInput: undefined,+ });++ let mobileScrollRef: HTMLDivElement | undefined;++ const registerRef = (name: keyof ComposeLayoutRefs) => {+ return (el: HTMLElement) => {+ setRefs((p) => ({ ...p, [name]: el }));+ };+ };++ const [attachComposeHotkeys, composeHotkeyScope] =+ useHotkeyDOMScope('compose-email');++ const [showCc, setShowCc] = createSignal(false);+ const [showBcc, setShowBcc] = createSignal(false);++ const isCcVisible = () => showCc() || ctx.recipients().cc.length > 0;+ const isBccVisible = () => showBcc() || ctx.recipients().bcc.length > 0;++ onMount(() => {+ const container = refs().containerRef;+ if (!container) return;+ attachComposeHotkeys(container);+ });++ // --- Hotkeys ---++ registerHotkey({+ hotkey: 'shift+cmd+o',+ scopeId: composeHotkeyScope,+ description: 'Edit "To" recipients',+ keyDownHandler: () => {+ refs()?.directRecipientsSelector?.focus();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: TOKENS.email.compose.edit.recipients,+ shouldReturnFocusOnClose: false,+ });++ registerHotkey({+ hotkey: 'shift+cmd+c',+ scopeId: composeHotkeyScope,+ description: 'Edit "Cc" recipients',+ keyDownHandler: () => {+ if (!showCc()) {+ setShowCc(true);+ queueMicrotask(() => refs()?.ccRecipientsSelector?.focus());+ return true;+ }+ refs()?.ccRecipientsSelector?.focus();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: TOKENS.email.compose.edit.ccRecipients,+ shouldReturnFocusOnClose: false,+ });++ registerHotkey({+ hotkey: 'shift+cmd+b',+ scopeId: composeHotkeyScope,+ description: 'Edit "Bcc" recipients',+ keyDownHandler: () => {+ if (!showBcc()) {+ setShowBcc(true);+ queueMicrotask(() => refs()?.bccRecipientsSelector?.focus());+ return true;+ }+ refs()?.bccRecipientsSelector?.focus();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: TOKENS.email.compose.edit.bccRecipients,+ shouldReturnFocusOnClose: false,+ });++ registerHotkey({+ hotkey: 'shift+cmd+s',+ scopeId: composeHotkeyScope,+ description: 'Edit subject',+ keyDownHandler: () => {+ refs()?.subjectInput?.focus();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: TOKENS.email.compose.edit.subject,+ shouldReturnFocusOnClose: false,+ });++ registerHotkey({+ hotkey: 'shift+cmd+m',+ scopeId: composeHotkeyScope,+ description: 'Edit message',+ keyDownHandler: () => {+ refs()?.messageInput?.focus();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: TOKENS.email.compose.edit.message,+ shouldReturnFocusOnClose: false,+ });++ registerHotkey({+ hotkey: 'cmd+enter',+ scopeId: composeHotkeyScope,+ description: 'Send email',+ keyDownHandler: () => {+ if (ctx.sendTime()) return false;+ ctx.onSend();+ return true;+ },+ runWithInputFocused: true,+ hotkeyToken: 'email.send',+ displayPriority: 10,+ });++ return (+ <>+ <Show when={!isMobile()}>+ <SplitHeaderLeft>+ <StaticSplitLabel+ class="ph-no-capture"+ label={ctx.subject() || props.previewName?.() || 'Draft email'}+ iconType="email"+ badges={[+ <SplitHeaderBadge text="draft" tooltip="This is a Draft Email" />,+ ]}+ />+ </SplitHeaderLeft>+ </Show>+ <div+ ref={registerRef('containerRef')}+ class="relative flex flex-col w-full h-full min-h-0 overflow-hidden text-sm"+ >+ <Show when={hasLinkError()}>+ <EmailPermissionsBanner />+ </Show>++ <div+ ref={mobileScrollRef}+ class="macro-message-width sm:macro-message-padding mx-auto w-full max-h-full my-2 sm:my-12 mobile:my-0 px-2 sm:px-4 mobile:px-0 overflow-hidden mobile:overflow-y-auto mobile:hide-scrollbar mobile:min-h-full"+ classList={{+ 'pointer-events-none opacity-50': hasLinkError(),+ }}+ >+ <WrapUnlessMobile+ wrapper={(children) => (+ <ClippedPanel tl={!beveledCorners()}>{children}</ClippedPanel>+ )}+ >+ <div+ class="w-full p-4 bg-input max-h-full mobile:max-h-none overflow-y-auto flex flex-col min-h-0 mobile:min-h-full"+ classList={{+ 'pointer-events-none opacity-50': hasLinkError(),+ }}+ >+ <div class="macro-message-width mx-auto pb-1 w-full h-max shrink-0">+ <div class="mb-4 h-6 flex items-center justify-between">+ <Show+ when={props.header}+ fallback={+ <Suspense+ fallback={+ <div class="flex gap-1 items-center">+ <CircleSpinner class="w-4 h-4 animate-spin" />+ <span class="text-ink-extra-muted/50 text-xs">+ Processing...+ </span>+ </div>+ }+ >+ <Show when={ctx.fromAddress?.()}>+ {(addr) => (+ <div class="text-xs text-ink-extra-muted/50">+ from {addr()}+ </div>+ )}+ </Show>+ </Suspense>+ }+ >+ {props.header}+ </Show>+ <div class="flex gap-2 ml-auto">+ <Show when={!isCcVisible()}>+ <button+ type="button"+ class="text-ink-muted hover:text-ink hover:bg-hover"+ onClick={() => setShowCc(true)}+ disabled={hasLinkError()}+ >+ + Cc+ </button>+ </Show>+ <Show when={!isBccVisible()}>+ <button+ type="button"+ class="text-ink-muted hover:text-ink hover:bg-hover"+ onClick={() => setShowBcc(true)}+ disabled={hasLinkError()}+ >+ + Bcc+ </button>+ </Show>+ </div>+ </div>++ <ComposeRecipients+ toRef={registerRef('directRecipientsSelector')}+ ccRef={registerRef('ccRecipientsSelector')}+ bccRef={registerRef('bccRecipientsSelector')}+ showCc={showCc}+ setShowCc={setShowCc}+ showBcc={showBcc}+ setShowBcc={setShowBcc}+ />++ <ComposeSubject inputRef={registerRef('subjectInput')} />+ </div>++ <div+ class="w-full h-full flex flex-col min-h-0 mt-4"+ classList={{+ 'pointer-events-none opacity-50': hasLinkError(),+ }}+ >+ <ComposeBody+ inputRef={registerRef('messageInput')}+ mobileScrollRef={() => mobileScrollRef}+ onAddFiles={(files) => {+ ctx.onAddAttachments(+ files.map((file) => ({ type: 'local', file }))+ );+ }}+ />+ {props.toolbar ?? ctx.toolbar?.()}+ </div>+ </div>+ </WrapUnlessMobile>+ </div>+ </div>+ </>+ );+}diff --git a/js/app/packages/block-email/component/compose/ComposeRecipients.tsx b/js/app/packages/block-email/component/compose/ComposeRecipients.tsxnew file mode 100644index 0000000000..bea504593f--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeRecipients.tsx@@ -0,0 +1,192 @@+import type { EmailRecipient } from '@block-email/component/EmailContext';+import { RecipientSelector } from '@core/component/RecipientSelector';+import { createSignal, Show } from 'solid-js';+import { type RecipientFieldId, useCompose } from './ComposeContext';++type DragState = {+ recipient: EmailRecipient;+ sourceField: RecipientFieldId;+};++function ComposeFieldRow(props: {+ label: string;+ children: import('solid-js').JSX.Element;+ fieldId?: RecipientFieldId;+ dragState?: () => DragState | null;+ onRecipientDrop?: (+ recipient: EmailRecipient,+ sourceField: RecipientFieldId+ ) => void;+}) {+ const [isDragOver, setIsDragOver] = createSignal(false);++ const handleDragOver = (e: DragEvent) => {+ const drag = props.dragState?.();+ if (!drag || !props.fieldId || drag.sourceField === props.fieldId) return;+ e.preventDefault();+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';+ setIsDragOver(true);+ };++ const handleDragLeave = () => {+ setIsDragOver(false);+ };++ const handleDrop = (e: DragEvent) => {+ e.preventDefault();+ setIsDragOver(false);+ const drag = props.dragState?.();+ if (!drag || !props.fieldId || drag.sourceField === props.fieldId) return;+ props.onRecipientDrop?.(drag.recipient, drag.sourceField);+ };++ return (+ <div+ class="flex items-center gap-2 border-b border-edge-muted focus-within:border-accent"+ classList={{ 'border-accent bg-accent/10': isDragOver() }}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ <div class="text-sm w-7 shrink-0 text-ink-placeholder/70">+ {props.label}+ </div>+ <div class="flex-1">{props.children}</div>+ </div>+ );+}++export function ComposeRecipients(props: {+ toRef?: (el: HTMLElement) => void;+ ccRef?: (el: HTMLElement) => void;+ bccRef?: (el: HTMLElement) => void;+ showCc: () => boolean;+ setShowCc: (v: boolean) => void;+ showBcc: () => boolean;+ setShowBcc: (v: boolean) => void;+}) {+ const ctx = useCompose();++ const isCcVisible = () => props.showCc() || ctx.recipients().cc.length > 0;+ const isBccVisible = () => props.showBcc() || ctx.recipients().bcc.length > 0;++ const [recipientDragState, setRecipientDragState] =+ createSignal<DragState | null>(null);++ const handleChipDragStart = (+ field: RecipientFieldId,+ recipient: EmailRecipient,+ e: DragEvent+ ) => {+ if (!e.dataTransfer) return;+ setRecipientDragState({ recipient, sourceField: field });+ e.dataTransfer.effectAllowed = 'move';+ e.dataTransfer.setData('text/plain', '');+ };++ const handleChipDragEnd = () => {+ setRecipientDragState(null);+ };++ const handleRecipientDrop = (+ targetField: RecipientFieldId,+ recipient: EmailRecipient,+ sourceField: RecipientFieldId+ ) => {+ const sourceList = ctx.recipients()[sourceField];+ ctx.setRecipients(+ sourceField,+ sourceList.filter((r) => r.id !== recipient.id)+ );+ const targetList = ctx.recipients()[targetField];+ if (!targetList.some((r) => r.id === recipient.id)) {+ ctx.setRecipients(targetField, [...targetList, recipient]);+ }+ if (targetField === 'cc') props.setShowCc(true);+ if (targetField === 'bcc') props.setShowBcc(true);+ };++ return (+ <div class="flex flex-col gap-2">+ <ComposeFieldRow+ label="To"+ fieldId="to"+ dragState={recipientDragState}+ onRecipientDrop={(recipient, sourceField) =>+ handleRecipientDrop('to', recipient, sourceField)+ }+ >+ <RecipientSelector+ inputRef={props.toRef}+ options={ctx.recipientOptions}+ selectedOptions={ctx.recipients().to}+ setSelectedOptions={(next) => ctx.setRecipients('to', next)}+ placeholder="Macro users or email addresses"+ focusOnMount={ctx.focusRecipientsOnMount}+ hideBorder+ noBrackets+ disabled={ctx.disabled()}+ onChipDragStart={(option, e) => handleChipDragStart('to', option, e)}+ onChipDragEnd={handleChipDragEnd}+ />+ <Show when={ctx.validationError('no_recipient')}>+ {(err) => (+ <div class="text-failure-ink text-sm mt-1">{err().message}</div>+ )}+ </Show>+ </ComposeFieldRow>++ <Show when={isCcVisible()}>+ <ComposeFieldRow+ label="Cc"+ fieldId="cc"+ dragState={recipientDragState}+ onRecipientDrop={(recipient, sourceField) =>+ handleRecipientDrop('cc', recipient, sourceField)+ }+ >+ <RecipientSelector+ inputRef={props.ccRef}+ options={ctx.recipientOptions}+ selectedOptions={ctx.recipients().cc}+ setSelectedOptions={(next) => ctx.setRecipients('cc', next)}+ placeholder="Macro users or email addresses"+ hideBorder+ noBrackets+ disabled={ctx.disabled()}+ onChipDragStart={(option, e) =>+ handleChipDragStart('cc', option, e)+ }+ onChipDragEnd={handleChipDragEnd}+ />+ </ComposeFieldRow>+ </Show>++ <Show when={isBccVisible()}>+ <ComposeFieldRow+ label="Bcc"+ fieldId="bcc"+ dragState={recipientDragState}+ onRecipientDrop={(recipient, sourceField) =>+ handleRecipientDrop('bcc', recipient, sourceField)+ }+ >+ <RecipientSelector+ inputRef={props.bccRef}+ options={ctx.recipientOptions}+ selectedOptions={ctx.recipients().bcc}+ setSelectedOptions={(next) => ctx.setRecipients('bcc', next)}+ placeholder="Macro users or email addresses"+ hideBorder+ noBrackets+ disabled={ctx.disabled()}+ onChipDragStart={(option, e) =>+ handleChipDragStart('bcc', option, e)+ }+ onChipDragEnd={handleChipDragEnd}+ />+ </ComposeFieldRow>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/block-email/component/compose/ComposeSubject.tsx b/js/app/packages/block-email/component/compose/ComposeSubject.tsxnew file mode 100644index 0000000000..127e07af37--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeSubject.tsx@@ -0,0 +1,30 @@+import { Show } from 'solid-js';+import { useCompose } from './ComposeContext';++export function ComposeSubject(props: {+ inputRef?: (el: HTMLElement) => void;+}) {+ const ctx = useCompose();++ return (+ <div class="w-full flex items-center gap-2 border-b border-edge-muted focus-within:border-accent py-2">+ <div class="shrink-0 text-ink-placeholder/70">Subject</div>+ <div class="flex-1">+ <input+ ref={props.inputRef}+ type="text"+ value={ctx.subject()}+ placeholder="Subject"+ class="w-full resize-none placeholder:text-ink-placeholder p-1 ml-1"+ onInput={(e) => ctx.setSubject(e.currentTarget.value)}+ disabled={ctx.disabled()}+ />+ </div>+ <Show when={ctx.validationError('no_subject')}>+ {(err) => (+ <div class="text-failure-ink text-sm mt-1">{err().message}</div>+ )}+ </Show>+ </div>+ );+}diff --git a/js/app/packages/block-email/component/compose/ComposeToolbar.tsx b/js/app/packages/block-email/component/compose/ComposeToolbar.tsxnew file mode 100644index 0000000000..fdd2e38ce8--- /dev/null+++ b/js/app/packages/block-email/component/compose/ComposeToolbar.tsx@@ -0,0 +1,234 @@+import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHeader';+import { FormatRibbon } from '@block-channel/component/FormatRibbon';+import { EmailDateSelector } from '@block-email/component/email-date-selector';+import { MAX_ATTACHMENTS_BYTES_SIZE } from '@block-email/constants';+import { Button } from '@ui/components/Button';+import { DropdownMenuContent, MenuItem } from '@core/component/Menu';+import { toast } from '@core/component/Toast/Toast';+import { Tooltip } from '@core/component/Tooltip';+import { ENABLE_EMAIL_SCHEDULED_SEND } from '@core/constant/featureFlags';+import { fileSelector } from '@core/directive/fileSelector';+import { isMobile } from '@core/mobile/isMobile';+import { plural } from '@core/util/string';+import ArrowUp from '@icon/bold/arrow-up-bold.svg';+import TextAa from '@icon/regular/text-aa.svg';+import Trash from '@icon/regular/trash.svg';+import { DropdownMenu } from '@kobalte/core/dropdown-menu';+import PaperPlane from '@macro-icons/wide/paper-plane-cutout.svg';+import DotsThreeIcon from '@phosphor-icons/core/bold/dots-three-bold.svg?component-solid';+import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';+import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';+import PaperclipHorizontalIcon from '@phosphor-icons/core/regular/paperclip-horizontal.svg?component-solid';+import { defaultSelectionData } from 'core/component/LexicalMarkdown/plugins';+import {+ NODE_TRANSFORM,+ type NodeTransformType,+} from 'core/component/LexicalMarkdown/plugins/node-transform/nodeTransformPlugin';+import {+ FORMAT_TEXT_COMMAND,+ type LexicalEditor,+ type TextFormatType,+} from 'lexical';+import { createSignal, Show } from 'solid-js';+import { useCompose } from './ComposeContext';++export function EmailComposeToolbar(props: {+ editor?: () => LexicalEditor | undefined;+}) {+ const ctx = useCompose();+ const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);+ let attachButtonRef!: HTMLDivElement;++ const handleAddAttachments = (files: File[]) => {+ const currentAttachments = ctx.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;+ }++ ctx.onAddAttachments(+ files.map((file) => ({+ type: 'local',+ file,+ }))+ );+ };++ return (+ <>+ <Show when={showFormatRibbon()}>+ <FormatRibbon+ class="-ml-3"+ state={structuredClone(defaultSelectionData)}+ inlineFormat={(format: TextFormatType) => {+ props.editor?.()?.dispatchCommand(FORMAT_TEXT_COMMAND, format);+ }}+ nodeFormat={(transform: NodeTransformType) => {+ props.editor?.()?.dispatchCommand(NODE_TRANSFORM, transform);+ }}+ />+ </Show>+ <div class="flex flex-row w-full h-8 justify-between items-center space-x-2 allow-css-brackets mt-2">+ <Show+ when={!isMobile()}+ fallback={+ <MobileToolbar+ attachButtonRef={attachButtonRef}+ handleAddAttachments={handleAddAttachments}+ />+ }+ >+ <div class="flex flex-row items-center gap-2">+ <div class="relative" ref={attachButtonRef}>+ <Button+ ref={(el) =>+ fileSelector(el, () => ({+ multiple: true,+ onSelect: handleAddAttachments,+ }))+ }+ tooltip="Attach"+ class="aspect-square p-1"+ disabled={ctx.disabled()}+ >+ <PaperclipIcon class="h-5" />+ </Button>+ </div>+ <Button+ variant="ghost"+ size="icon-sm"+ disabled={ctx.disabled()}+ onClick={() => {+ setShowFormatRibbon(!showFormatRibbon());+ }}+ >+ <TextAa />+ </Button>+ <Show when={ENABLE_EMAIL_SCHEDULED_SEND && ctx.onSendTimeChange}>+ <EmailDateSelector+ sendTime={ctx.sendTime()}+ onSendTimeChange={ctx.onSendTimeChange}+ disabled={ctx.scheduleSendDisabled?.()}+ />+ </Show>+ <Show when={ctx.hasDraft() && !ctx.isDraftSaving()}>+ <Button+ onclick={ctx.onDelete}+ tooltip="Delete draft"+ class="aspect-square *:h-5 p-1"+ >+ <Trash />+ </Button>+ </Show>+ <Show when={ctx.isDraftSaving()}>+ <div class="aspect-square p-1 flex items-center justify-center">+ <Spinner class="size-5 animate-spin text-ink-muted" />+ </div>+ </Show>+ </div>++ <Tooltip+ tooltip={ctx.sendTime() ? 'Send time is scheduled' : undefined}+ >+ <button+ disabled={ctx.isSending() || ctx.disabled() || !!ctx.sendTime()}+ onClick={() => ctx.onSend()}+ 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={!ctx.isSending()}+ 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">+ <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />+ </div>+ </Show>+ </button>+ </Tooltip>+ </Show>+ </div>+ </>+ );+}++function MobileToolbar(props: {+ attachButtonRef: HTMLDivElement;+ handleAddAttachments: (files: File[]) => void;+}) {+ const ctx = useCompose();++ return (+ <SplitHeaderRight>+ <div class="flex items-center pl-2">+ <div class="relative" ref={props.attachButtonRef}>+ <Button+ ref={(el) =>+ fileSelector(el, () => ({+ multiple: true,+ onSelect: props.handleAddAttachments,+ }))+ }+ tooltip="Attach"+ class="aspect-square p-1"+ disabled={ctx.disabled()}+ >+ <PaperclipHorizontalIcon class="h-5" />+ </Button>+ </div>+ <Show when={ENABLE_EMAIL_SCHEDULED_SEND && ctx.onSendTimeChange}>+ <EmailDateSelector+ sendTime={ctx.sendTime()}+ onSendTimeChange={ctx.onSendTimeChange}+ disabled={ctx.scheduleSendDisabled?.()}+ compact+ />+ </Show>+ <Tooltip+ tooltip={ctx.sendTime() ? 'Send time is scheduled' : undefined}+ >+ <Button+ disabled={ctx.isSending() || ctx.disabled() || !!ctx.sendTime()}+ onClick={() => ctx.onSend()}+ >+ <PaperPlane class="size-4.5 text-accent" />+ </Button>+ </Tooltip>+ <DropdownMenu placement="bottom-end">+ <DropdownMenu.Trigger as={Button} class="aspect-square p-1">+ <DotsThreeIcon class="h-4.5" />+ </DropdownMenu.Trigger>+ <DropdownMenu.Portal>+ <DropdownMenuContent>+ <MenuItem+ text="Delete Draft"+ disabled={!ctx.hasDraft()}+ onClick={ctx.onDelete}+ />+ </DropdownMenuContent>+ </DropdownMenu.Portal>+ </DropdownMenu>+ </div>+ </SplitHeaderRight>+ );+}diff --git a/js/app/packages/block-email/component/compose/index.ts b/js/app/packages/block-email/component/compose/index.tsnew file mode 100644index 0000000000..324d83b574--- /dev/null+++ b/js/app/packages/block-email/component/compose/index.ts@@ -0,0 +1,11 @@+export { EmailCompose } from './Compose';+export { ComposeProvider, useCompose } from './ComposeContext';+export type {+ ComposeContextValue,+ ComposeValidationError,+} from './ComposeContext';+export { ComposeLayout } from './ComposeLayout';+export { ComposeBody } from './ComposeBody';+export { ComposeRecipients } from './ComposeRecipients';+export { ComposeSubject } from './ComposeSubject';+export { EmailComposeToolbar } from './ComposeToolbar';diff --git a/js/app/packages/entity/src/components/CollapsibleList.tsx b/js/app/packages/entity/src/components/CollapsibleList.tsxindex df9ca71287..a13af6a4f7 100644--- a/js/app/packages/entity/src/components/CollapsibleList.tsx+++ b/js/app/packages/entity/src/components/CollapsibleList.tsx@@ -1,6 +1,6 @@-import { For, Show, createSignal, onCleanup, type JSX } from 'solid-js';import ChevronDownIcon from '@icon/regular/caret-down.svg?component-solid';import { cn } from '@ui/utils/classname';+import { createSignal, For, type JSX, onCleanup, Show } from 'solid-js';interface CollapsibleListProps<T> {items: T[];