import React from 'react'; import { View, Text, StyleSheet, TextInput, Pressable, ScrollView, Keyboard, Platform, ActivityIndicator, Alert, Modal, useWindowDimensions, } from 'react-native'; import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'; import { usePreventRemove } from '@react-navigation/native'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import { X, Send, Paperclip, ChevronDown, Bold, Italic, Underline, Strikethrough, List, ListOrdered, Link2, Link2Off, Image as ImageIcon, Quote, Heading1, Heading2, AlignLeft, AlignCenter, AlignRight, RemoveFormatting, Undo2, Redo2, FileText, Clock, Check, Palette, Table, LayoutTemplate, MailCheck, Users, Tag, Type, Highlighter, } from '../components/icons'; import DateTimePicker, { type DateTimePickerEvent } from '@react-native-community/datetimepicker'; import * as ImagePicker from 'expo-image-picker'; import * as DocumentPicker from 'expo-document-picker'; import * as FileSystem from 'expo-file-system/legacy'; import * as Sharing from 'expo-sharing'; import * as Clipboard from 'expo-clipboard'; import { spacing, radius, typography, componentSizes, type ThemePalette } from '../theme/tokens'; import { useColors } from '../theme/colors'; import { Button, IdentitySheet } from '../components'; import { TemplateSheet } from '../components/TemplateSheet'; import RichTextEditor, { type RichTextEditorHandle, type RichTextSelectionState, } from '../components/RichTextEditor'; import { useEmailStore } from '../stores/email-store'; import { ownMailboxes } from '../lib/mailbox-tree'; import { getEmailInitials } from '../lib/avatar-utils'; import { useContactsStore, type RecipientSuggestion } from '../stores/contacts-store'; import { useKeyboardObstruction } from '../lib/use-keyboard-obstruction'; import { useLayout } from '../lib/use-layout'; import { useLocaleStore } from '../stores/locale-store'; import { useSettingsStore } from '../stores/settings-store'; import { useHasContacts } from '../lib/capabilities'; import { isTrustedSendersSyncOn } from '../lib/trusted-senders'; import { useAccountStore } from '../stores/account-store'; import { useSendUndoStore } from '../stores/send-undo-store'; import { toast } from '../stores/toast-store'; import { type EmailTemplate } from '../stores/templates-store'; import { getIdentities } from '../api/identity'; import { sendEmail, saveDraftVersion, destroyEmails, patchKeywordsForEmails, type OutgoingAttachment, type OutgoingEmail, } from '../api/email'; import { jmapClient, RequestTimeoutError, ScheduleTooLateError } from '../api/jmap-client'; import { uploadBlob, uploadBytes } from '../api/blob'; import { buildReplyRecipients, type ReplySource } from '../lib/reply-recipients'; import { buildReplySubject, buildForwardSubject } from '../lib/subject-prefix'; import { computeReplyThreadingHeaders, generateMessageId, stripMessageIdBrackets } from '../lib/email-threading'; import { escapeHtml, stripDangerousTags } from '../lib/email-html'; import { buildInitialHtml, htmlToPlainText, rewriteInlineImages, extractUserAuthoredText, rewriteCidImagesForEditor, replaceInlineImagePlaceholders, sniffImageMime, QUOTED_BLOCK_START, } from '../lib/compose-html'; import { htmlComposeBodyToPlainText, initialPlainTextMode, plainComposeBodyToHtml } from '../lib/compose-format'; import { buildQuoteHeader, formatQuoteDate, quoteHeaderLabels, type QuoteHeaderLabels } from '../lib/quote-header'; import { isValidEmail, splitPastedRecipients, expandRecipients, parseRecipient, type Recipient as ParsedRecipient, } from '../lib/recipients'; import { findComposeIdentityId, findDraftIdentityId, resolveComposeAccountEmail, resolveReplyIdentity, } from '../lib/reply-identity'; import { shouldBlockEditorRemoteImages } from '../lib/editor-html'; import { initialDraftPartBlobState, liveBlobId, rebaseDraftPartBlobs, withSnapshotBody, } from '../lib/draft-part-blobs'; import { signatureIdentityFor, buildEmbeddedSignatureHtml, containsEmbeddedSignature, spliceSignature, insertSignatureAboveQuote, getPlainTextSignature, appendPlainTextSignature, plainTextBodyHasSignature, plainTextBodyWithoutSignature, SIGNATURE_RANGE_MARKER, wantsSignatureSeparator, } from '../lib/signature-utils'; import { getAutoFilledPlaceholders, getPlaceholdersFromTemplate, substitutePlaceholders, templateBodyToHtml, } from '../lib/template-utils'; import { generateSubAddress, extractDomain, suggestTagsForDomain, getTagValidationError, MAX_TAG_LENGTH, } from '../lib/sub-addressing'; import { sanitizeDisplayName } from '../lib/rfc5322-mailbox'; import type { EmailAddress, Identity } from '../api/types'; import type { RootStackParamList } from '../navigation/types'; import { MODAL_ORIENTATIONS } from '../lib/modal-orientations'; import ToggleSwitch from '../components/ToggleSwitch'; type Props = NativeStackScreenProps; /** A recipient chip. Group chips carry their resolved members and no email. */ interface Recipient { name: string; email: string; group?: { members: Array<{ name?: string; email: string }> }; } type AttachmentEntry = { localId: string; name: string; type: string; size: number; uri: string; inline: boolean; cid?: string; blobId?: string; uploading: boolean; /** 0..1 while uploading, when the transport reports it. */ progress?: number; error?: string; abort?: AbortController; }; type Field = 'to' | 'cc' | 'bcc'; const URL_RE = /^https?:\/\/.+/i; // The webmail's 2 x 8 palette, used for text and background colour alike. const TEXT_COLORS = [ '#000000', '#5f6368', '#9aa0a6', '#c5221f', '#e8710a', '#f9ab00', '#188038', '#1967d2', '#7627bb', '#c2185b', '#795548', '#fa5252', '#fd7e14', '#40c057', '#4dabf7', '#e64980', ]; function formatBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; return `${(n / (1024 * 1024)).toFixed(1)} MB`; } function genCid(): string { return `${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 10)}@bulwark.local`; } function genLocalId(): string { return `${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}`; } async function readUriAsDataUrl(uri: string, mime: string): Promise { try { const base64 = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64, }); return `data:${mime};base64,${base64}`; } catch { return null; } } const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function bytesToBase64(bytes: Uint8Array): string { let out = ''; let i = 0; for (; i + 2 < bytes.length; i += 3) { const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + B64[n & 63]; } if (i < bytes.length) { const rem = bytes.length - i; const n = (bytes[i] << 16) | (rem === 2 ? bytes[i + 1] << 8 : 0); out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (rem === 2 ? B64[(n >> 6) & 63] : '=') + '='; } return out; } function toRecipient(r: { name?: string | null; email?: string | null }): Recipient | null { if (!r.email) return null; return { name: r.name ?? '', email: r.email }; } function toRecipientList(list: Array<{ name?: string | null; email?: string | null }> | undefined | null): Recipient[] { return (list ?? []).map(toRecipient).filter((r): r is Recipient => !!r); } function fromParsed(r: ParsedRecipient): Recipient { return { name: r.name ?? '', email: r.email, group: r.group }; } function toAddress(r: { name?: string; email: string }): EmailAddress { return r.name ? { name: r.name, email: r.email } : { email: r.email }; } function chipIsValid(r: Recipient): boolean { return r.group ? r.group.members.length > 0 : isValidEmail(r.email); } /** Strip the editor's structural markers before the HTML leaves the device. */ function stripEditorMarkers(html: string): string { return html .replace(new RegExp(`\\s${SIGNATURE_RANGE_MARKER}=("[^"]*"|'[^']*')`, 'g'), '') .replace(/\sdata-quoted-html=("[^"]*"|'[^']*')/g, ''); } function quoteLines(text: string): string { return text.split('\n').map((l) => `> ${l}`).join('\n'); } function RecipientChip({ recipient, invalid, onRemove, onLongPress, }: { recipient: Recipient; invalid?: boolean; onRemove: () => void; onLongPress?: () => void; }) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); const t = useLocaleStore((s) => s.t); const label = recipient.group ? t('email_composer.group_chip', '{name} ({count})', { name: recipient.name || t('contacts.group', 'Group'), count: recipient.group.members.length, }) : recipient.name || recipient.email; return ( {recipient.group && } {label} ); } function initialsOf(name: string, email: string): string { return getEmailInitials(name.trim(), email); } function SuggestionList({ suggestions, onPick, onPressIn, }: { suggestions: RecipientSuggestion[]; onPick: (s: RecipientSuggestion) => void; onPressIn?: () => void; }) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); const t = useLocaleStore((s) => s.t); return ( {suggestions.map((s, i) => ( onPick(s)} style={({ pressed }) => [styles.suggestionRow, pressed && styles.suggestionRowPressed]} > {s.group ? : {initialsOf(s.name, s.email)}} {s.name || s.email} {s.group ? ( {t('contacts.groups.member_count', '{count, plural, =0 {No members} one {1 member} other {# members}}', { count: s.group.memberCount })} ) : !!s.name && ( {s.email} )} ))} ); } function AttachmentChip({ attachment, onRemove, onPress, }: { attachment: AttachmentEntry; onRemove: () => void; onPress: () => void; }) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); const t = useLocaleStore((s) => s.t); const pct = attachment.progress != null ? Math.round(attachment.progress * 100) : null; return ( {attachment.uploading ? ( ) : attachment.error ? ( ) : attachment.type.startsWith('image/') ? ( ) : ( )} {attachment.name} {attachment.error ? attachment.error : attachment.uploading ? pct != null ? t('email_composer.uploading_pct', 'Uploading {pct}%', { pct }) : t('email_composer.uploading', 'Uploading...') : formatBytes(attachment.size)} {attachment.uploading && pct != null && ( )} ); } function ToolbarButton({ active, onPress, icon, disabled, label, }: { active?: boolean; onPress: () => void; icon: React.ReactNode; disabled?: boolean; label?: string; }) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); return ( {icon} ); } interface SheetOption { label: string; destructive?: boolean; onPress: () => void; } /** Simple action list (Android's Alert caps at three buttons). */ function OptionsSheet({ visible, title, options, onClose, cancelLabel, }: { visible: boolean; title?: string; options: SheetOption[]; onClose: () => void; cancelLabel: string; }) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); return ( {}}> {!!title && {title}} {options.map((opt) => ( { onClose(); opt.onPress(); }} > {opt.label} ))} {cancelLabel} ); } export default function ComposeScreen({ route, navigation }: Props) { const c = useColors(); const styles = React.useMemo(() => makeStyles(c), [c]); const t = useLocaleStore((s) => s.t); const locale = useLocaleStore((s) => s.locale); const timeFormat = useSettingsStore((s) => s.timeFormat); const insets = useSafeAreaInsets(); // Track the visible keyboard obstruction so the format bar stays above it. const kbObstruction = useKeyboardObstruction(insets.bottom, () => editorRef.current?.blur()); const { shortHeight, isSplit } = useLayout(); const typingInShortWindow = shortHeight && kbObstruction > 0; // When the keyboard is up it covers the bottom safe area, so we don't // need to add it on top — pad by whichever is larger. // On a tablet the composer is a centred panel that stops PANEL_MARGIN // short of the screen bottom; the keyboard covers that much less of it. const bottomPad = isSplit ? Math.max(0, kbObstruction - PANEL_MARGIN) : Math.max(kbObstruction, insets.bottom); const replyTo = route.params?.replyTo; const draft = route.params?.draft; const mode = route.params?.mode ?? 'compose'; const prefillTo = route.params?.prefillTo; const prefillCc = route.params?.prefillCc; const prefillBcc = route.params?.prefillBcc; const prefillSubject = route.params?.prefillSubject; const prefillBody = route.params?.prefillBody; const prefillAttachments = route.params?.prefillAttachments; const isReplyLike = !!replyTo && !draft; const mailboxes = useEmailStore((s) => s.mailboxes); // Always the user's own Sent — composing on behalf of a shared account // isn't supported, so a group account's Sent must never be picked up here. const sentMailbox = React.useMemo( () => ownMailboxes(mailboxes).find((m) => m.role === 'sent'), [mailboxes], ); // The message is created in Drafts and moved to Sent by the submission's // onSuccessUpdateEmail, so a failed send never leaves a fake sent copy (#188). const draftsMailbox = React.useMemo( () => ownMailboxes(mailboxes).find((m) => m.role === 'drafts'), [mailboxes], ); const [identities, setIdentities] = React.useState([]); const [identityError, setIdentityError] = React.useState(null); const [sending, setSending] = React.useState(false); const [selectedIdentityId, setSelectedIdentityId] = React.useState(null); const [identitySheetOpen, setIdentitySheetOpen] = React.useState(false); const [scheduleSheetOpen, setScheduleSheetOpen] = React.useState(false); // Custom date/time picker stage. iOS shows one 'datetime' spinner; Android // can only show one field at a time, so we walk date → time. const [customStage, setCustomStage] = React.useState<'datetime' | 'date' | 'time' | null>(null); const customDraftRef = React.useRef(new Date()); const autoSelectReplyIdentity = useSettingsStore((s) => s.autoSelectReplyIdentity); const replyIdentityMatch = useSettingsStore((s) => s.replyIdentityMatch); // Per-message format (#1022): seeded from the "plain text only" setting, // or the format a reopened draft was written in, and switchable from the // toolbar for just this message. const plainTextSetting = useSettingsStore((s) => s.plainTextMode); const [plainTextMode, setPlainTextMode] = React.useState(() => initialPlainTextMode(draft, plainTextSetting)); const attachmentReminderEnabled = useSettingsStore((s) => s.attachmentReminderEnabled); const attachmentReminderKeywords = useSettingsStore((s) => s.attachmentReminderKeywords); const sendDelaySeconds = useSettingsStore((s) => s.sendDelaySeconds); const signaturePosition = useSettingsStore((s) => s.signaturePosition); const signatureSeparatorEnabled = useSettingsStore((s) => s.signatureSeparatorEnabled); const requestReadReceiptDefault = useSettingsStore((s) => s.requestReadReceiptDefault); const emptySubjectWarningEnabled = useSettingsStore((s) => s.emptySubjectWarningEnabled); const autoSaveDraftInterval = useSettingsStore((s) => s.autoSaveDraftInterval); const subAddressDelimiter = useSettingsStore((s) => s.subAddressDelimiter); const preferredIdentityIds = useSettingsStore((s) => s.preferredIdentityIds); const trustedSendersAddressBook = useSettingsStore((s) => s.trustedSendersAddressBook); const hasContacts = useHasContacts(); const updateSetting = useSettingsStore((s) => s.updateSetting); const quoteLabels = React.useMemo(() => quoteHeaderLabels(t), [t]); // Every address that is "us": the login, the account's primary address and // every identity. Reply-all must not send the user a copy, and replying to // a self-sent message continues to its original recipients (#703). const ownEmails = React.useMemo(() => { const out = new Set(); const active = useAccountStore.getState().getActiveAccount(); for (const e of [active?.email, active?.username, jmapClient.username]) { if (e && e.includes('@')) out.add(e); } for (const i of identities) if (i.email) out.add(i.email); return Array.from(out); }, [identities]); const replySource = React.useMemo( () => (replyTo ? { from: replyTo.from.email ? [replyTo.from] : [], replyToAddresses: replyTo.replyToAddresses, to: replyTo.to, cc: replyTo.cc, } : undefined), [replyTo], ); const initialTo = React.useMemo(() => { if (draft) return toRecipientList(draft.to); if (!replyTo) return toRecipientList(prefillTo); if (mode === 'forward') return []; return toRecipientList( buildReplyRecipients(replySource, mode === 'replyAll' ? 'replyAll' : 'reply', ownEmails).to, ); // Seeds state once; identity-based refinement happens in the effect below. // eslint-disable-next-line react-hooks/exhaustive-deps }, [replyTo, draft, mode, prefillTo]); const initialCc = React.useMemo(() => { if (draft) return toRecipientList(draft.cc); if (!replyTo) return toRecipientList(prefillCc); if (mode !== 'replyAll') return []; return toRecipientList(buildReplyRecipients(replySource, 'replyAll', ownEmails).cc); // eslint-disable-next-line react-hooks/exhaustive-deps }, [replyTo, draft, mode, prefillCc]); const initialBcc = React.useMemo( () => (draft ? toRecipientList(draft.bcc) : toRecipientList(prefillBcc)), // eslint-disable-next-line react-hooks/exhaustive-deps [draft], ); const initialSubject = React.useMemo(() => { if (draft) return draft.subject ?? ''; if (!replyTo) return prefillSubject ?? ''; // Strip stacked / foreign-language prefixes (AW:, WG:, Re[2]:) before // adding the locale's own so the chain doesn't grow on every hop. if (mode === 'forward') { return buildForwardSubject(replyTo.subject, t('email_composer.prefix.forward', 'Fwd:')); } return buildReplySubject(replyTo.subject, t('email_composer.prefix.reply', 'Re:')); }, [replyTo, draft, mode, prefillSubject, t]); // The quoted HTML with `cid:` images swapped for placeholders that carry // the cid; the hydration effect below fetches the blobs (#163/#543). const seedHtml = React.useMemo(() => { const raw = draft ? draft.htmlBody : replyTo?.htmlBody; if (!raw) return { html: undefined as string | undefined, cids: [] as string[] }; const { html, cids } = rewriteCidImagesForEditor(stripDangerousTags(raw)); return { html, cids }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // Remote images in a quoted original stay blocked in the editor whenever // the viewer blocks them; the sent HTML keeps them. Read once: the editor // page is built on mount. const blockRemoteImages = React.useMemo(() => { const settings = useSettingsStore.getState(); const sender = replyTo?.from.email?.trim().toLowerCase(); return shouldBlockEditorRemoteImages({ seedHtml: draft ? draft.htmlBody : replyTo?.htmlBody, isDraft: !!draft, externalContentPolicy: settings.externalContentPolicy, senderTrusted: !!sender && ( settings.isSenderTrusted(sender) || useContactsStore.getState().trustedSenderEmails.includes(sender) ), }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const initialBodyHtml = React.useMemo( () => { if (draft) { if (seedHtml.html) return seedHtml.html; if (draft.textBody) return `
${escapeHtml(draft.textBody).replace(/\r?\n/g, '
')}
`; return '


'; } if (!replyTo) { return prefillBody ? `
${escapeHtml(prefillBody).replace(/\r?\n/g, '
')}


` : '


'; } // Quick reply "More options" hands the typed text over as prefillBody; // it goes above the quote. const typed = prefillBody ? `
${escapeHtml(prefillBody).replace(/\r?\n/g, '
')}
` : ''; return typed + buildInitialHtml(mode, { from: { name: replyTo.from.name, email: replyTo.from.email }, to: replyTo.to, cc: replyTo.cc, subject: replyTo.subject, body: replyTo.body, htmlBody: seedHtml.html, receivedAt: replyTo.sentAt ?? replyTo.receivedAt, }, { timeFormat, locale, unknownLabel: t('common.unknown', 'Unknown'), labels: quoteLabels }); }, // eslint-disable-next-line react-hooks/exhaustive-deps [], ); // Plain-text mode seed: the same quote as text, `> `-prefixed for replies. const initialPlainBody = React.useMemo(() => { if (draft) return draft.textBody ?? (draft.htmlBody ? htmlToPlainText(stripDangerousTags(draft.htmlBody)) : ''); if (!replyTo) return prefillBody ?? ''; const header = buildQuoteHeader({ mode: mode === 'compose' ? 'reply' : mode, email: { from: replyTo.from, subject: replyTo.subject, receivedAt: replyTo.sentAt ?? replyTo.receivedAt }, timeFormat, locale, unknownLabel: t('common.unknown', 'Unknown'), labels: quoteLabels, }); const body = replyTo.body ?? (replyTo.htmlBody ? htmlToPlainText(stripDangerousTags(replyTo.htmlBody)) : ''); if (!body) return ''; if (mode === 'forward') return `\n\n${header.text}\n${body}`; return `\n\n${header.text}${quoteLines(body)}`; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // Attachments carried over from the original (forward) or the re-opened // draft. Blobs are account-scoped: a message in a shared/group account has // to be re-uploaded into the user's own account before it can be sent. // Inline images referenced from the quoted body are hydrated separately // and never shown as file chips. const seedAttachments = replyTo?.attachments ?? draft?.attachments; const seedOwnerAccountId = replyTo?.jmapAccountId ?? draft?.jmapAccountId; const seedCidSet = React.useMemo(() => new Set(seedHtml.cids), [seedHtml.cids]); const isSeedInline = React.useCallback( (a: { cid?: string; disposition?: string }) => !!a.cid && seedCidSet.has(stripMessageIdBrackets(a.cid)), [seedCidSet], ); const initialAttachments = React.useMemo(() => { if (!seedAttachments?.length) return []; return seedAttachments .filter((a) => !!a.blobId && !isSeedInline(a)) .map((a) => ({ localId: `seed-${a.blobId}`, name: a.name || 'attachment', type: a.type || 'application/octet-stream', size: a.size ?? 0, uri: '', inline: false, blobId: seedOwnerAccountId ? undefined : a.blobId, uploading: !!seedOwnerAccountId, })); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const [toRecipients, setToRecipients] = React.useState(initialTo); const [ccRecipients, setCcRecipients] = React.useState(initialCc); const [bccRecipients, setBccRecipients] = React.useState(initialBcc); const [ccVisible, setCcVisible] = React.useState(initialCc.length > 0 || initialBcc.length > 0); const [bccVisible, setBccVisible] = React.useState(initialBcc.length > 0); const [toInput, setToInput] = React.useState(''); const [ccInput, setCcInput] = React.useState(''); const [bccInput, setBccInput] = React.useState(''); const [subject, setSubject] = React.useState(initialSubject); const [bodyHtml, setBodyHtml] = React.useState(initialBodyHtml); // What the editor page is built from when it mounts: the initial body, or // the converted one after a switch from plain text. const [editorSeedHtml, setEditorSeedHtml] = React.useState(initialBodyHtml); const [plainBody, setPlainBody] = React.useState(initialPlainBody); const plainSelectionRef = React.useRef<{ start: number; end: number } | null>(null); const [activeField, setActiveField] = React.useState(null); const [attachments, setAttachments] = React.useState(initialAttachments); const [requestReadReceipt, setRequestReadReceipt] = React.useState(requestReadReceiptDefault); const [subAddressTag, setSubAddressTag] = React.useState(''); const [fromOverride, setFromOverride] = React.useState<{ name: string; email: string } | null>(null); const [selState, setSelState] = React.useState({ bold: false, italic: false, underline: false, strikeThrough: false, ul: false, ol: false, blockquote: false, h1: false, h2: false, alignLeft: false, alignCenter: false, alignRight: false, link: false, }); const editorRef = React.useRef(null); // The label column grows with the system font size: at 1.3 "Betreff" // wrapped into "Betref" / "f" in a fixed 56 dp column. const { fontScale } = useWindowDimensions(); const fieldLabelWidth = React.useMemo(() => ({ width: Math.round(56 * Math.max(1, fontScale)) }), [fontScale]); const subjectRef = React.useRef(null); const plainBodyRef = React.useRef(null); const [subjectFocused, setSubjectFocused] = React.useState(false); // The composer's ScrollView and its live offset. On Android the editor page // hands back the caret-reveal pans it undoes (see `pinVisualViewport` in // editor-html); scrolling the composer by the same amount keeps the caret // where the pan had put it, without leaving the body drawn shifted up. const bodyScrollRef = React.useRef(null); const bodyScrollY = React.useRef(0); const onEditorViewportShift = React.useCallback((dy: number) => { const y = Math.max(0, bodyScrollY.current + dy); bodyScrollY.current = y; bodyScrollRef.current?.scrollTo({ y, animated: false }); }, []); const isPickingSuggestion = React.useRef(false); // Track inline-image placeholders that haven't yet been rewritten to cid: // until send time. Maps cid → blobId/type/name/size. const inlineRegistryRef = React.useRef>(new Map()); // A re-opened draft's attachments and inline images are parts of that // draft: their blobIds die with each version a save replaces (#849), and an // upload expires once nothing references it. This maps the blobId each // entry holds to the matching part of the latest saved version, which // `buildOutgoing` sends. Kept out of the attachment state so the dirty // snapshot does not change on every save. const draftPartBlobsRef = React.useRef(initialDraftPartBlobState()); const getAutocomplete = useContactsStore((s) => s.getAutocomplete); const getGroupRecipients = useContactsStore((s) => s.getGroupRecipients); const loadRecentRecipients = useContactsStore((s) => s.loadRecentRecipients); const contactsVersion = useContactsStore((s) => s.contacts); const recentVersion = useContactsStore((s) => s.recentRecipients); React.useEffect(() => { if (sentMailbox?.id) void loadRecentRecipients(sentMailbox.id); }, [sentMailbox?.id, loadRecentRecipients]); const inputFor = (field: Field | null) => field === 'to' ? toInput : field === 'cc' ? ccInput : field === 'bcc' ? bccInput : ''; const suggestionQuery = inputFor(activeField); const alreadySelected = React.useMemo( () => new Set( [...toRecipients, ...ccRecipients, ...bccRecipients] .flatMap((r) => (r.group ? r.group.members.map((m) => m.email) : [r.email])) .map((e) => e.toLowerCase()), ), [toRecipients, ccRecipients, bccRecipients], ); const suggestions = React.useMemo(() => { const q = suggestionQuery.trim(); if (q.length < 1) return []; return getAutocomplete(q, 16) .filter((s) => s.group || !alreadySelected.has(s.email.toLowerCase())) .slice(0, 8); // contactsVersion/recentVersion re-run the lookup when the store loads. // eslint-disable-next-line react-hooks/exhaustive-deps }, [suggestionQuery, alreadySelected, getAutocomplete, contactsVersion, recentVersion]); const setterFor = (field: Field) => field === 'to' ? setToRecipients : field === 'cc' ? setCcRecipients : setBccRecipients; const inputSetterFor = (field: Field) => field === 'to' ? setToInput : field === 'cc' ? setCcInput : setBccInput; const pickSuggestion = (s: RecipientSuggestion) => { isPickingSuggestion.current = true; const field = activeField ?? 'to'; let recipient: Recipient; if (s.group) { const members = getGroupRecipients(s.group.id) .filter((m) => !alreadySelected.has(m.email.toLowerCase())) .map((m) => ({ name: m.name || undefined, email: m.email })); if (members.length === 0) { inputSetterFor(field)(''); return; } recipient = { name: s.name, email: '', group: { members } }; } else { recipient = { name: s.name, email: s.email }; } setterFor(field)((prev) => [...prev, recipient]); inputSetterFor(field)(''); }; React.useEffect(() => { let cancelled = false; void (async () => { try { const list = await getIdentities(); if (!cancelled) setIdentities(list); } catch (e) { if (!cancelled) { setIdentityError(e instanceof Error ? e.message : 'Failed to load identities'); } } })(); return () => { cancelled = true; }; }, []); // Once the identities are known, recompute the reply recipients so every // own alias is dropped from a reply-all (the initial seed only knew the // login address). Skipped when the user already edited the fields. const recipientsRefinedRef = React.useRef(false); React.useEffect(() => { if (recipientsRefinedRef.current || identities.length === 0) return; if (!isReplyLike || mode === 'forward') return; recipientsRefinedRef.current = true; const sameList = (a: Recipient[], b: Recipient[]) => a.length === b.length && a.every((r, i) => r.email === b[i].email); if (!sameList(toRecipients, initialTo) || !sameList(ccRecipients, initialCc)) return; const { to, cc } = buildReplyRecipients( replySource, mode === 'replyAll' ? 'replyAll' : 'reply', ownEmails, ); const nextTo = toRecipientList(to); const nextCc = toRecipientList(cc); if (!sameList(nextTo, toRecipients)) setToRecipients(nextTo); if (!sameList(nextCc, ccRecipients)) { setCcRecipients(nextCc); if (nextCc.length > 0) setCcVisible(true); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [identities]); // Re-upload attachments that live in another account's blob store (forward // from a shared folder) into the user's own account. React.useEffect(() => { if (!seedOwnerAccountId || !seedAttachments?.length) return; let cancelled = false; void (async () => { for (const a of seedAttachments) { if (!a.blobId || isSeedInline(a)) continue; const localId = `seed-${a.blobId}`; try { const buf = await jmapClient.fetchBlobArrayBuffer(a.blobId, a.name, a.type, seedOwnerAccountId); const up = await uploadBytes(new Uint8Array(buf), a.type || 'application/octet-stream'); if (!cancelled) updateAttachment(localId, { blobId: up.blobId, size: up.size, uploading: false }); } catch (e) { if (!cancelled) { updateAttachment(localId, { uploading: false, error: e instanceof Error ? e.message : t('email_composer.upload_failed_short', 'Upload failed'), }); } } } })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // Hydrate the quoted original's inline images: fetch each cid's blob, show // it as a data URL and register the part so it is re-attached inline on // send (#163/#543). Cross-account blobs are re-uploaded into our account. React.useEffect(() => { if (seedHtml.cids.length === 0 || !seedAttachments?.length) return; let cancelled = false; void (async () => { const map = new Map(); for (const cid of seedHtml.cids) { const att = seedAttachments.find((a) => a.cid && stripMessageIdBrackets(a.cid) === cid && a.blobId); if (!att?.blobId) continue; try { const buf = await jmapClient.fetchBlobArrayBuffer(att.blobId, att.name, att.type, seedOwnerAccountId); const bytes = new Uint8Array(buf); const mime = att.type?.toLowerCase().startsWith('image/') ? att.type : (sniffImageMime(bytes) ?? 'image/png'); map.set(cid, `data:${mime};base64,${bytesToBase64(bytes)}`); let blobId = att.blobId; if (seedOwnerAccountId) blobId = (await uploadBytes(bytes, mime)).blobId; inlineRegistryRef.current.set(cid, { localId: `cid-${cid}`, name: att.name || 'image', type: mime, size: att.size ?? bytes.byteLength, uri: '', inline: true, cid, blobId, uploading: false, }); } catch (err) { console.warn('[compose] inline image hydration failed', err); } } if (cancelled || map.size === 0) return; // No change message since the editor loaded = the user has not typed // yet, so the editor still holds the seeded body (normalised by the // WebView DOM, which is why it can differ from the raw server HTML). const untouched = !plainTextMode && latestRef.current.bodyHtml === initialBodyHtml; let live = latestRef.current.bodyHtml; try { live = (await editorRef.current?.getHtml()) ?? live; } catch { /* fall back to the last change message */ } const next = replaceInlineImagePlaceholders(live, map); if (next !== live) { setBodyHtml(next); editorRef.current?.setHtml(next); } // The hydrated images are part of the untouched baseline, not an edit. if (untouched) { // Rebase on the body the composer now holds: comparing it with the // raw server HTML made every re-opened draft with inline images look // edited, and the autosave replaced (and destroyed) it unasked. baselineRef.current = withSnapshotBody(baselineRef.current, next); if (lastSavedRef.current) lastSavedRef.current = withSnapshotBody(lastSavedRef.current, next); } else { baselineRef.current = replaceInlineImagePlaceholders(baselineRef.current, map); if (lastSavedRef.current) lastSavedRef.current = replaceInlineImagePlaceholders(lastSavedRef.current, map); } })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // A new message started while a shared folder is open sends as that // mailbox's owner when the user has an identity for it (webmail 129f545a). // Read once: it is the folder the message was started from. Own folders // resolve to nothing, so they keep the preferred identity below. const composeFromAccountEmail = React.useMemo(() => { const { mailboxes: all, currentMailboxId } = useEmailStore.getState(); return resolveComposeAccountEmail(all, currentMailboxId); }, []); // Choose the identity once we know both the loaded identities and the // compose context: a re-opened draft keeps the identity it was written // with; a new message in a shared folder uses that folder's identity; a // reply or forward sends from the own identity the original was delivered // to (a reply to our own message, from the one that sent it); with // auto-select on, a reply to a catch-all alias on an owned domain takes // that address as a From override; otherwise the preferred ("Use as // default") identity, else the one matching the active account. React.useEffect(() => { if (selectedIdentityId || identities.length === 0) return; const activeEmail = useAccountStore.getState().getActiveAccount()?.email || jmapClient.username; const preferredId = preferredIdentityIds[jmapClient.accountId]; const defaultIdentity = identities.find((i) => i.id === preferredId) ?? identities.find((i) => i.email.toLowerCase() === activeEmail?.toLowerCase()) ?? identities.find((i) => !i.mayDelete) ?? identities[0]; if (draft) { const matched = findDraftIdentityId(identities, draft.from?.[0]); setSelectedIdentityId(matched ?? defaultIdentity.id); return; } if (!replyTo) { const composeId = findComposeIdentityId(identities, composeFromAccountEmail); if (composeId) { setSelectedIdentityId(composeId); return; } } if (replyTo) { // The catch-all From rewrite is opt-in and never used on a forward. const resolved = resolveReplyIdentity(identities, replyTo, { ownEmails, catchAll: autoSelectReplyIdentity && mode !== 'forward', matchMode: replyIdentityMatch, }); if (resolved) { setSelectedIdentityId(resolved.identityId); if (resolved.overrideEmail) { setFromOverride({ name: resolved.overrideName ?? '', email: resolved.overrideEmail }); } return; } } setSelectedIdentityId(defaultIdentity.id); // eslint-disable-next-line react-hooks/exhaustive-deps }, [identities, autoSelectReplyIdentity, replyIdentityMatch, replyTo, draft, selectedIdentityId, preferredIdentityIds]); const primaryIdentity = React.useMemo(() => { if (identities.length === 0) return null; const activeEmail = useAccountStore.getState().getActiveAccount()?.email || jmapClient.username; const defaultIdentity = identities.find( (i) => i.email.toLowerCase() === activeEmail?.toLowerCase() ) ?? identities[0]; return identities.find((i) => i.id === selectedIdentityId) ?? defaultIdentity; }, [identities, selectedIdentityId]); // An alias without a signature falls back to the primary identity's. const signatureIdentity = React.useMemo( () => signatureIdentityFor(primaryIdentity, identities), [primaryIdentity, identities], ); const openIdentityPicker = () => { if (identities.length <= 1) return; setIdentitySheetOpen(true); }; // ── Recipients ─────────────────────────────────────────────────────── // Typed-but-uncommitted text is parsed the same way a paste is; leftovers // that are not addresses count as invalid and block Send. const typedRecipients = React.useMemo(() => { const parseField = (input: string, existing: Recipient[]) => { if (!input.trim()) return { valid: [] as Recipient[], invalid: [] as string[] }; const { valid, invalid } = splitPastedRecipients(input, Array.from(alreadySelected)); return { valid: valid.map(fromParsed).filter((r) => !existing.some((e) => e.email.toLowerCase() === r.email.toLowerCase())), invalid, }; }; return { to: parseField(toInput, toRecipients), cc: parseField(ccInput, ccRecipients), bcc: parseField(bccInput, bccRecipients), }; }, [toInput, ccInput, bccInput, toRecipients, ccRecipients, bccRecipients, alreadySelected]); const finalTo = React.useMemo(() => [...toRecipients, ...typedRecipients.to.valid], [toRecipients, typedRecipients]); const finalCc = React.useMemo(() => [...ccRecipients, ...typedRecipients.cc.valid], [ccRecipients, typedRecipients]); const finalBcc = React.useMemo(() => [...bccRecipients, ...typedRecipients.bcc.valid], [bccRecipients, typedRecipients]); const invalidTyped = [...typedRecipients.to.invalid, ...typedRecipients.cc.invalid, ...typedRecipients.bcc.invalid]; // Move what was typed into chips (blur / submit). Unparseable leftovers // stay in the input so nothing the user typed is silently dropped. const addTyped = (field?: Field) => { const fields: Field[] = field ? [field] : ['to', 'cc', 'bcc']; for (const f of fields) { const parsed = typedRecipients[f]; if (parsed.valid.length) { setterFor(f)((prev) => { const existing = new Set(prev.flatMap((r) => (r.group ? r.group.members.map((m) => m.email) : [r.email])).map((e) => e.toLowerCase())); const unique = parsed.valid.filter((r) => !existing.has(r.email.toLowerCase())); return unique.length ? [...prev, ...unique] : prev; }); } const leftover = parsed.invalid.join(' '); if (leftover !== inputFor(f)) inputSetterFor(f)(leftover); } }; const [chipMenu, setChipMenu] = React.useState<{ field: Field; index: number } | null>(null); const chipMenuRecipient = chipMenu ? (chipMenu.field === 'to' ? toRecipients : chipMenu.field === 'cc' ? ccRecipients : bccRecipients)[chipMenu.index] : null; const removeChip = (field: Field, index: number) => setterFor(field)((prev) => prev.filter((_, i) => i !== index)); const moveChip = (from: Field, index: number, to: Field) => { const list = from === 'to' ? toRecipients : from === 'cc' ? ccRecipients : bccRecipients; const r = list[index]; if (!r) return; removeChip(from, index); setterFor(to)((prev) => [...prev, r]); if (to === 'cc') setCcVisible(true); if (to === 'bcc') { setCcVisible(true); setBccVisible(true); } }; const chipMenuOptions = React.useMemo(() => { if (!chipMenu || !chipMenuRecipient) return []; const r = chipMenuRecipient; const fieldLabel = (f: Field) => (f === 'to' ? t('email_composer.to', 'To') : f === 'cc' ? t('email_composer.cc', 'Cc') : t('email_composer.bcc', 'Bcc')); const opts: SheetOption[] = []; for (const target of (['to', 'cc', 'bcc'] as Field[]).filter((f) => f !== chipMenu.field)) { opts.push({ label: t('email_composer.recipient_move_to', 'Move to {field}', { field: fieldLabel(target) }), onPress: () => moveChip(chipMenu.field, chipMenu.index, target), }); } if (!r.group) { opts.push({ label: t('email_composer.recipient_copy', 'Copy address'), onPress: () => { void Clipboard.setStringAsync(r.email); }, }); opts.push({ label: t('email_composer.recipient_add_contact', 'Add to contacts'), onPress: () => navigation.navigate('ContactForm', { prefill: { email: r.email, name: r.name || undefined } }), }); } opts.push({ label: t('email_composer.recipient_remove', 'Remove'), destructive: true, onPress: () => removeChip(chipMenu.field, chipMenu.index), }); return opts; // eslint-disable-next-line react-hooks/exhaustive-deps }, [chipMenu, chipMenuRecipient, t]); const hasUploadInFlight = attachments.some((a) => a.uploading); const hasUploadError = attachments.some((a) => !!a.error); const allChipsValid = [...finalTo, ...finalCc, ...finalBcc].every(chipIsValid); const hasValidRecipients = finalTo.length > 0 && allChipsValid && invalidTyped.length === 0; const bodyPlain = React.useMemo( () => (plainTextMode ? plainBody : htmlToPlainText(bodyHtml)), [plainTextMode, plainBody, bodyHtml], ); const hasBodyContent = bodyPlain.trim().length > 0 || attachments.some((a) => a.blobId && !a.error); const canSend = !sending && !hasUploadInFlight && !hasUploadError && hasValidRecipients && hasBodyContent && !!primaryIdentity && !!sentMailbox; // ── Dirty tracking / drafts ────────────────────────────────────────── const snapshotOf = (s: { to: Recipient[]; cc: Recipient[]; bcc: Recipient[]; subject: string; body: string; attachments: AttachmentEntry[]; }) => JSON.stringify({ to: s.to.map((r) => [r.name, r.email, r.group?.members.map((m) => m.email)]), cc: s.cc.map((r) => [r.name, r.email, r.group?.members.map((m) => m.email)]), bcc: s.bcc.map((r) => [r.name, r.email, r.group?.members.map((m) => m.email)]), subject: s.subject, body: s.body, att: s.attachments.filter((a) => !a.inline).map((a) => a.blobId ?? a.localId), }); // Memoized: the snapshot copies the whole body, and the screen re-renders // for plenty that doesn't touch it (PF8). const currentSnapshot = React.useMemo(() => snapshotOf({ to: finalTo, cc: finalCc, bcc: finalBcc, subject, body: plainTextMode ? plainBody : bodyHtml, attachments, // eslint-disable-next-line react-hooks/exhaustive-deps }), [finalTo, finalCc, finalBcc, subject, plainTextMode, plainBody, bodyHtml, attachments]); const baselineRef = React.useRef(snapshotOf({ to: initialTo, cc: initialCc, bcc: initialBcc, subject: initialSubject, body: plainTextMode ? initialPlainBody : initialBodyHtml, attachments: initialAttachments, })); // Snapshot at the last successful draft save (null = never saved). const lastSavedRef = React.useRef(draft ? baselineRef.current : null); const draftIdRef = React.useRef(draft?.id ?? null); const messageIdRef = React.useRef(draft?.messageId?.[0] ?? null); const inflightSaveRef = React.useRef | null>(null); const saveTimerRef = React.useRef | null>(null); const lastSaveAtRef = React.useRef(0); const allowLeaveRef = React.useRef(false); const sendingRef = React.useRef(false); const [draftStatus, setDraftStatus] = React.useState<'idle' | 'saving' | 'saved' | 'failed'>('idle'); const [savingDraft, setSavingDraft] = React.useState(false); const [, bumpBaseline] = React.useReducer((n: number) => n + 1, 0); const isDirty = currentSnapshot !== baselineRef.current; const needsSave = currentSnapshot !== (lastSavedRef.current ?? baselineRef.current); // Latest state for callbacks that outlive a render (autosave timer, // beforeRemove listener, hydration). const latestRef = React.useRef({ bodyHtml, plainBody, isDirty, needsSave, currentSnapshot }); latestRef.current = { bodyHtml, plainBody, isDirty, needsSave, currentSnapshot }; // ── Signature ──────────────────────────────────────────────────────── const placeSignatureHtml = React.useCallback((html: string, sigHtml: string): string => { if (!sigHtml) return html; if (isReplyLike && signaturePosition === 'above_quote') { return insertSignatureAboveQuote(html, sigHtml, QUOTED_BLOCK_START); } return `${html}${sigHtml}`; }, [isReplyLike, signaturePosition]); const placeSignaturePlain = React.useCallback((body: string, identity: Identity): string => { const sig = getPlainTextSignature(identity); if (!sig) return body; const sep = wantsSignatureSeparator(signatureSeparatorEnabled, identity) ? '\n\n-- \n' : '\n\n'; if (isReplyLike && signaturePosition === 'above_quote') { const idx = body.indexOf('\n\n'); const head = idx === -1 ? body : body.slice(0, idx); const tail = idx === -1 ? '' : body.slice(idx); return `${head}${sep}${sig}${tail}`; } return appendPlainTextSignature(body, identity, { separator: signatureSeparatorEnabled }); }, [isReplyLike, signaturePosition, signatureSeparatorEnabled]); // Embed the signature once the identities are known. A re-opened draft // keeps whatever it already carries (#848). const signatureEmbeddedRef = React.useRef(false); const prevSignatureIdentityRef = React.useRef(null); React.useEffect(() => { if (!primaryIdentity) return; if (!signatureEmbeddedRef.current) { signatureEmbeddedRef.current = true; prevSignatureIdentityRef.current = signatureIdentity; if (draft || !signatureIdentity) return; if (plainTextMode) { const next = placeSignaturePlain(latestRef.current.plainBody, signatureIdentity); setPlainBody(next); baselineRef.current = snapshotOf({ to: initialTo, cc: initialCc, bcc: initialBcc, subject: initialSubject, body: next, attachments: initialAttachments, }); } else { const sigHtml = buildEmbeddedSignatureHtml(signatureIdentity, { separator: signatureSeparatorEnabled }); void (async () => { let live = latestRef.current.bodyHtml; try { live = (await editorRef.current?.getHtml()) ?? live; } catch { /* keep the last change message */ } if (containsEmbeddedSignature(live)) return; const next = placeSignatureHtml(live, sigHtml); setBodyHtml(next); editorRef.current?.setHtml(next); // The untouched baseline is the editor's own read-back: the page // normalises the markup, so the string built here never equalled // what it reports, and an untouched reply counted as edited (it // autosaved a draft and asked "Save or discard?" on close). let settled = placeSignatureHtml(initialBodyHtml, sigHtml); try { settled = (await editorRef.current?.getHtml()) ?? settled; } catch { /* keep the built string */ } if (latestRef.current.bodyHtml === next) setBodyHtml(settled); baselineRef.current = snapshotOf({ to: initialTo, cc: initialCc, bcc: initialBcc, subject: initialSubject, body: settled, attachments: initialAttachments, }); // The baseline is a ref: re-render so "edited" is worked out again. bumpBaseline(); })(); } return; } // Identity switch: swap the signature block, leaving the text alone. const prev = prevSignatureIdentityRef.current; if (prev?.id === signatureIdentity?.id) return; prevSignatureIdentityRef.current = signatureIdentity; if (plainTextMode) { setPlainBody((body) => { let stripped = body; if (prev && plainTextBodyHasSignature(body, prev)) { stripped = plainTextBodyWithoutSignature(body, prev); } else if (prev) { const old = getPlainTextSignature(prev); const marker = `${wantsSignatureSeparator(signatureSeparatorEnabled, prev) ? '\n\n-- \n' : '\n\n'}${old}`; if (old && body.includes(marker)) stripped = body.replace(marker, ''); } return signatureIdentity ? placeSignaturePlain(stripped, signatureIdentity) : stripped; }); return; } const sigHtml = signatureIdentity ? buildEmbeddedSignatureHtml(signatureIdentity, { separator: signatureSeparatorEnabled }) : ''; void (async () => { let live = latestRef.current.bodyHtml; try { live = (await editorRef.current?.getHtml()) ?? live; } catch { /* keep the last change message */ } const next = containsEmbeddedSignature(live) ? spliceSignature(live, sigHtml) : placeSignatureHtml(live, sigHtml); if (next !== live) { setBodyHtml(next); editorRef.current?.setHtml(next); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [primaryIdentity?.id, signatureIdentity?.id]); // ── Outgoing message assembly ───────────────────────────────────────── const senderAddress = React.useCallback((identity: Identity): { from: EmailAddress; envelopeMailFrom?: string } => { const name = sanitizeDisplayName(identity.name); let from: EmailAddress; if (fromOverride?.email.trim()) { const overrideName = sanitizeDisplayName(fromOverride.name); from = overrideName ? { name: overrideName, email: fromOverride.email.trim() } : { email: fromOverride.email.trim() }; } else { const email = subAddressTag ? generateSubAddress(identity.email, subAddressTag, subAddressDelimiter) : identity.email; from = name ? { name, email } : { email }; } // A From that isn't the identity's own address still goes out through // the identity's envelope sender. const envelopeMailFrom = from.email.toLowerCase() !== identity.email.toLowerCase() ? identity.email : undefined; return { from, envelopeMailFrom }; }, [fromOverride, subAddressTag, subAddressDelimiter]); const buildOutgoing = React.useCallback((identity: Identity, liveHtml: string, opts: { forDraft: boolean }): OutgoingEmail => { const { from, envelopeMailFrom } = senderAddress(identity); if (!messageIdRef.current) messageIdRef.current = generateMessageId(identity.email); let htmlBody: string | undefined; let textBody: string; let usedCids: string[] = []; if (plainTextMode) { textBody = plainBody; } else { const rewritten = rewriteInlineImages(liveHtml); usedCids = rewritten.usedCids; // Belt-and-suspenders sanitization: the editor uses execCommand which // can preserve pasted