import React from 'react'; import { View, Text, StyleSheet, Pressable } from 'react-native'; import { Star, ChevronDown, ChevronUp, Reply, Forward, ShieldCheck, ShieldAlert, ShieldQuestion, Lock, } from '../icons'; import type { Email, EmailAddress, Identity } from '../../api/types'; import { spacing, radius, typography, componentSizes, type ThemePalette } from '../../theme/tokens'; import { useColors } from '../../theme/colors'; import SenderAvatar from '../SenderAvatar'; import { useSettingsStore } from '../../stores/settings-store'; import { useLocaleStore } from '../../stores/locale-store'; import { useKeywordsStore, keywordToken } from '../../stores/keywords-store'; import { emailDisplayDate, formatHeaderDate, formatHeaderTime, formatFullDateTime } from '../../lib/email-date'; import { deriveHeaderInfo, deliveryDeltaMs, formatDelta, isAuthenticationSpoofed, findReceivingIdentity, type AuthenticationResults, type EmailHeaderInfo, } from '../../lib/email-headers'; import { formatSize } from '../../lib/attachment-display'; import { isSmimeEmail } from '../../lib/smime'; interface Props { email: Email; identities: Identity[]; headerInfo?: EmailHeaderInfo; onToggleStar?: (email: Email) => void; onAddressPress: (address: EmailAddress) => void; /** Compact variant for collapsed thread cards. */ compact?: boolean; } function addressLabel(a: EmailAddress): string { return a.name || a.email; } function AddressList({ label, addresses, onPress, styles, }: { label: string; addresses: EmailAddress[] | undefined; onPress: (a: EmailAddress) => void; styles: ReturnType }) { if (!addresses || addresses.length === 0) return null; return ( {label} {addresses.map((a, i) => ( onPress(a)} style={styles.recipientLink}> {addressLabel(a)}{i < addresses.length - 1 ? ', ' : ''} ))} ); } function authTone(result?: string): 'ok' | 'warn' | 'bad' | 'none' { switch (result) { case 'pass': return 'ok'; case 'fail': case 'permerror': return 'bad'; case 'softfail': case 'neutral': case 'temperror': return 'warn'; default: return 'none'; } } function AuthChip({ label, result, styles, c }: { label: string; result?: string; styles: ReturnType; c: ThemePalette }) { const t = useLocaleStore((s) => s.t); const tone = authTone(result); const color = tone === 'ok' ? c.success : tone === 'bad' ? c.error : tone === 'warn' ? c.warning : c.textMuted; const Icon = tone === 'ok' ? ShieldCheck : tone === 'bad' ? ShieldAlert : ShieldQuestion; return ( {label} {result ? t(`email_viewer.authentication.result.${result}`, result) : '-'} ); } function DetailRow({ label, value, styles, mono }: { label: string; value?: string | null; styles: ReturnType; mono?: boolean }) { if (!value) return null; return ( {label} {value} ); } /** * Sender / recipient / date block of a message, with the collapsible * "Show details" panel (recipients & routing, authentication, identifiers, * mailing list, properties) the webmail viewer shows. */ export function MessageHeader({ email, identities, headerInfo, onToggleStar, onAddressPress, compact }: 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 keywordDefs = useKeywordsStore((s) => s.keywords); const [showDetails, setShowDetails] = React.useState(false); React.useEffect(() => { setShowDetails(false); }, [email.id]); const info = React.useMemo(() => headerInfo ?? deriveHeaderInfo(email), [headerInfo, email]); const from = email.from?.[0]; const starred = !!email.keywords?.$flagged; const displayDate = emailDisplayDate(email); const spoofed = isAuthenticationSpoofed(info.auth); // "via ": the message was sent by one of the user's identities or // received at one of them (incl. +tag); hidden when the From can't be // trusted so a forged From doesn't get a legitimacy badge. const viaIdentity = React.useMemo(() => { if (spoofed || identities.length === 0) return null; const fromEmail = from?.email?.toLowerCase(); const sentAs = fromEmail ? identities.find((i) => i.email?.toLowerCase() === fromEmail) : undefined; if (sentAs) return { identity: sentAs, direction: 'from' as const }; const received = findReceivingIdentity(identities, email); if (received && identities.length > 1 && received.id !== identities[0].id) { return { identity: received, direction: 'to' as const }; } return null; }, [spoofed, identities, from?.email, email]); const tags = React.useMemo( () => keywordDefs.filter((kw) => !!email.keywords?.[keywordToken(kw.id)]), [keywordDefs, email.keywords], ); const important = !!email.keywords?.$important; const answered = !!email.keywords?.$answered; const forwarded = !!email.keywords?.$forwarded; const smime = React.useMemo(() => isSmimeEmail(email), [email]); const delta = deliveryDeltaMs(email); const auth: AuthenticationResults | undefined = info.auth; const hasAuth = !!(auth && (auth.spf || auth.dkim || auth.dmarc || auth.iprev)); const attachmentsSummary = email.attachments?.length ? t('email_viewer.details.attachment_count_size', '{count, plural, one {# file} other {# files}} · {size}', { count: email.attachments.length, size: formatSize(email.attachments.reduce((n, a) => n + (a.size ?? 0), 0)), }) : null; const receivedAt = formatFullDateTime(email.receivedAt, timeFormat, locale); return ( onAddressPress(from) : undefined} hitSlop={4} accessibilityRole="button" accessibilityLabel={from?.name || from?.email || t('email_viewer.unknown_sender', 'Unknown')} > onAddressPress(from) : undefined}> {from?.name || from?.email || t('email_viewer.unknown_sender', 'Unknown')} {from?.name && from?.email ? ( {from.email} ) : null} {!compact && ( <> )} {formatHeaderDate(displayDate, locale)} {formatHeaderTime(displayDate, timeFormat, locale)} {!compact && email.size > 0 ? ` · ${formatSize(email.size)}` : ''} {onToggleStar && ( onToggleStar(email)} hitSlop={8} style={styles.star} accessibilityRole="button" accessibilityLabel={starred ? t('email_viewer.unstar', 'Unstar') : t('email_viewer.star', 'Star')} > )} {(tags.length > 0 || important || answered || forwarded || viaIdentity || smime) && ( {important && ( {t('email_viewer.important', 'Important')} )} {tags.map((kw) => { const palette = c.tags[kw.color]; return ( {kw.label} ); })} {answered && ( {t('email_viewer.replied', 'Replied')} )} {forwarded && ( {t('email_viewer.forwarded', 'Forwarded')} )} {viaIdentity && ( {viaIdentity.direction === 'from' ? t('identities.badge.identity_short', 'via {name}', { name: viaIdentity.identity.email }) : t('email_viewer.received_via', 'to {name}', { name: viaIdentity.identity.email })} )} {smime && ( {t('email_viewer.smime_unsupported', 'Signed/encrypted with S/MIME - not supported on mobile')} )} )} {!compact && ( setShowDetails((v) => !v)} style={styles.detailsToggle} hitSlop={6}> {showDetails ? : } {showDetails ? t('email_viewer.hide_details', 'Hide details') : t('email_viewer.show_details', 'Show details')} )} {showDetails && ( {t('email_viewer.details.recipients_routing', 'Recipients & routing')} ` : undefined} styles={styles} /> a.name ? `${a.name} <${a.email}>` : a.email).join(', ')} styles={styles} /> a.name ? `${a.name} <${a.email}>` : a.email).join(', ')} styles={styles} /> a.name ? `${a.name} <${a.email}>` : a.email).join(', ')} styles={styles} /> 60000 ? t('email_viewer.details.received_after_delay', '{date} · {delay} delivery time', { date: receivedAt, delay: formatDelta(delta) }) : receivedAt} styles={styles} /> {(hasAuth || info.spamScore || info.spamLLM) && ( <> {t('email_viewer.details.authentication_security', 'Authentication & security')} {auth?.spf && } {auth?.dkim && } {auth?.dmarc && } {auth?.iprev && } {spoofed && ( {t('email_viewer.authentication.spoof_warning', 'The sender address could not be verified - this message may be spoofed.')} )} )} {t('email_viewer.details.identifiers_threading', 'Identifiers & threading')} {(info.list.listId || info.list.listHelp || info.list.listPost || info.list.listUnsubscribe) && ( <> {t('email_viewer.details.mailing_list', 'Mailing list')} )} {t('email_viewer.details.message_properties', 'Message properties')} )} ); } function makeStyles(c: ThemePalette) { return StyleSheet.create({ block: { backgroundColor: c.background, paddingHorizontal: spacing.lg, paddingVertical: spacing.md, gap: spacing.sm, }, row: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.md }, info: { flex: 1, minWidth: 0 }, name: { ...typography.bodySemibold, color: c.text }, email: { ...typography.caption, color: c.textSecondary, marginTop: 2 }, recipients: { ...typography.caption, color: c.textSecondary, marginTop: 4 }, recipientsLabel: { color: c.textMuted }, recipientLink: { color: c.textSecondary }, meta: { alignItems: 'flex-end', paddingTop: 1, gap: 2 }, date: { ...typography.caption, color: c.textSecondary }, time: { ...typography.caption, color: c.textMuted }, star: { paddingTop: 4 }, badges: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs }, badge: { flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: spacing.sm, paddingVertical: 2, borderRadius: radius.full, backgroundColor: c.surfaceHover, }, badgeDot: { width: 8, height: 8, borderRadius: 4 }, badgeText: { ...typography.small, color: c.textSecondary }, detailsToggle: { flexDirection: 'row', alignItems: 'center', gap: 4, alignSelf: 'flex-start' }, detailsToggleText: { ...typography.caption, color: c.primary, fontWeight: '600' }, details: { backgroundColor: c.surface, borderWidth: 1, borderColor: c.border, borderRadius: radius.md, padding: spacing.md, gap: spacing.xs, }, detailsSection: { ...typography.small, color: c.textMuted, textTransform: 'uppercase', marginTop: spacing.xs, letterSpacing: 0.5 }, detailRow: { flexDirection: 'row', gap: spacing.sm }, detailLabel: { ...typography.caption, color: c.textMuted, width: 92 }, detailValue: { ...typography.caption, color: c.text, flex: 1 }, detailMono: { fontFamily: 'monospace', fontSize: 11 }, chips: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs, marginBottom: spacing.xs }, chip: { flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: spacing.sm, paddingVertical: 3, borderRadius: radius.full, borderWidth: 1, }, chipText: { ...typography.small }, }); }