// 写信 / 编辑草稿弹窗
import { useMemo, useRef, useState } from 'react';
import { api, ApiError } from '../api';
import { Modal } from '../components/Modal';
import { Icon } from '../components/Icon';
import { InlineError, Spinner } from '../components/ui';
import { useI18n } from '../i18n';
import type {
Account,
AppSettings,
ComposeAttachment,
DraftData,
} from '../types';
import { fileToBase64, formatBytes } from '../utils';
const MAX_TOTAL = 25 * 1024 * 1024;
export function Compose({
accounts,
settings,
draft,
onClose,
onSent,
onDraftSaved,
onError,
onInfo,
}: {
accounts: Account[];
settings: AppSettings;
draft: DraftData | null;
onClose: () => void;
onSent: () => void;
onDraftSaved: () => void;
onError: (message: string) => void;
onInfo: (message: string) => void;
}) {
const { t } = useI18n();
const fileInputRef = useRef<HTMLInputElement>(null);
const defaultAccountId = useMemo(() => {
if (draft?.accountId && accounts.some((a) => a.id === draft.accountId)) return draft.accountId;
if (
settings.editor.defaultAccountId &&
accounts.some((a) => a.id === settings.editor.defaultAccountId)
) {
return settings.editor.defaultAccountId;
}
return accounts[0]?.id || 0;
}, [accounts, draft, settings.editor.defaultAccountId]);
const initialBody = useMemo(() => {
if (draft) return draft.bodyText;
const signature = settings.editor.signature?.trim();
return signature ? `\n\n--\n${signature}` : '';
}, [draft, settings.editor.signature]);
const [accountId, setAccountId] = useState(defaultAccountId);
const [to, setTo] = useState(draft?.to || '');
const [cc, setCc] = useState(draft?.cc || '');
const [bcc, setBcc] = useState(draft?.bcc || '');
const [showCc, setShowCc] = useState(Boolean(draft?.cc));
const [showBcc, setShowBcc] = useState(Boolean(draft?.bcc));
const [subject, setSubject] = useState(draft?.subject || '');
const [body, setBody] = useState(initialBody);
const [existing, setExisting] = useState(draft?.attachments || []);
const [added, setAdded] = useState<ComposeAttachment[]>([]);
const [error, setError] = useState('');
const [sending, setSending] = useState(false);
const [saving, setSaving] = useState(false);
const totalSize =
existing.reduce((sum, item) => sum + item.size, 0) +
added.reduce((sum, item) => sum + item.size, 0);
const editorStyle = {
fontFamily:
settings.editor.fontFamily === 'serif'
? 'Georgia, "Songti SC", "SimSun", serif'
: '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
fontSize: `${settings.editor.fontSize}px`,
lineHeight: settings.editor.lineHeight,
};
const pickFiles = async (files: FileList | null) => {
if (!files?.length) return;
const picked: ComposeAttachment[] = [];
for (const file of Array.from(files)) {
if (totalSize + picked.reduce((s, a) => s + a.size, 0) + file.size > MAX_TOTAL) {
onError(t('attachmentTooLarge'));
break;
}
try {
const data = await fileToBase64(file);
picked.push({
filename: file.name,
mime: file.type || 'application/octet-stream',
size: file.size,
data,
});
} catch {
onError(t('requestFailed'));
}
}
setAdded((prev) => [...prev, ...picked]);
if (fileInputRef.current) fileInputRef.current.value = '';
};
const validate = (): boolean => {
if (!accountId) {
setError(t('selectAccountError'));
return false;
}
if (!to.trim()) {
setError(t('noRecipientError'));
return false;
}
return true;
};
const handleSend = async () => {
setError('');
if (!validate()) return;
setSending(true);
try {
await api.send({
accountId,
to,
cc: showCc ? cc : '',
bcc: showBcc ? bcc : '',
subject,
text: body,
attachments: added.map((item) => ({
filename: item.filename,
mime: item.mime,
data: item.data,
})),
draftId: draft?.id,
keepAttachmentIds: draft ? existing.map((item) => item.id) : undefined,
});
onInfo(t('sendOk'));
onSent();
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.message : t('networkError'));
} finally {
setSending(false);
}
};
const handleSaveDraft = async () => {
setError('');
if (!accountId) {
setError(t('selectAccountError'));
return;
}
setSaving(true);
try {
await api.drafts.save({
id: draft?.id,
accountId,
to,
cc: showCc ? cc : '',
bcc: showBcc ? bcc : '',
subject,
bodyText: body,
attachments: added.map((item) => ({
filename: item.filename,
mime: item.mime,
data: item.data,
})),
keepAttachmentIds: draft ? existing.map((item) => item.id) : undefined,
});
onInfo(t('draftSaved'));
onDraftSaved();
onClose();
} catch (err) {
setError(err instanceof ApiError ? err.message : t('networkError'));
} finally {
setSaving(false);
}
};
return (
<Modal
title={draft ? t('draftEditHint') : t('writeMessage')}
onClose={onClose}
wide
footer={
<>
<button
type="button"
className="btn"
onClick={handleSaveDraft}
disabled={sending || saving}
>
{saving ? <Spinner /> : null}
{t('saveDraft')}
</button>
<div className="spacer" />
<button type="button" className="btn" onClick={onClose} disabled={sending}>
{t('cancel')}
</button>
<button type="button" className="btn btn-primary" onClick={handleSend} disabled={sending}>
{sending ? <Spinner /> : <Icon name="send" size={15} />}
{sending ? t('sending') : t('send')}
</button>
</>
}
>
<div className="compose">
<div className="compose-row">
<span className="compose-label">{t('from')}</span>
<select
className="input compose-select"
value={accountId}
onChange={(event) => setAccountId(Number(event.target.value))}
>
{accounts.map((account) => (
<option key={account.id} value={account.id}>
{account.name} · {account.email}
</option>
))}
</select>
</div>
<div className="compose-row">
<span className="compose-label">{t('to')}</span>
<input
className="input"
value={to}
onChange={(event) => setTo(event.target.value)}
placeholder="[email protected]"
/>
<div className="compose-row-actions">
{!showCc && (
<button type="button" className="link-btn" onClick={() => setShowCc(true)}>
{t('cc')}
</button>
)}
{!showBcc && (
<button type="button" className="link-btn" onClick={() => setShowBcc(true)}>
{t('bcc')}
</button>
)}
</div>
</div>
{showCc && (
<div className="compose-row">
<span className="compose-label">{t('cc')}</span>
<input className="input" value={cc} onChange={(event) => setCc(event.target.value)} />
</div>
)}
{showBcc && (
<div className="compose-row">
<span className="compose-label">{t('bcc')}</span>
<input className="input" value={bcc} onChange={(event) => setBcc(event.target.value)} />
</div>
)}
<div className="compose-row">
<span className="compose-label">{t('subject')}</span>
<input
className="input"
value={subject}
onChange={(event) => setSubject(event.target.value)}
/>
</div>
<textarea
className="compose-body"
style={editorStyle}
value={body}
onChange={(event) => setBody(event.target.value)}
/>
{(existing.length > 0 || added.length > 0) && (
<div className="attachment-bar">
{existing.map((att) => (
<span key={`old-${att.id}`} className="attachment-chip">
<Icon name="file" size={14} />
<span className="attachment-name">{att.filename}</span>
<span className="attachment-size">{formatBytes(att.size)}</span>
<button
type="button"
className="chip-remove"
onClick={() => setExisting((prev) => prev.filter((item) => item.id !== att.id))}
aria-label={t('delete')}
>
<Icon name="close" size={12} />
</button>
</span>
))}
{added.map((att, index) => (
<span key={`new-${index}-${att.filename}`} className="attachment-chip">
<Icon name="file" size={14} />
<span className="attachment-name">{att.filename}</span>
<span className="attachment-size">{formatBytes(att.size)}</span>
<button
type="button"
className="chip-remove"
onClick={() => setAdded((prev) => prev.filter((_, i) => i !== index))}
aria-label={t('delete')}
>
<Icon name="close" size={12} />
</button>
</span>
))}
</div>
)}
<div className="compose-toolbar">
<button
type="button"
className="btn btn-ghost btn-small"
onClick={() => fileInputRef.current?.click()}
>
<Icon name="paperclip" size={15} />
{t('addAttachment')}
</button>
{totalSize > 0 && <span className="compose-size">{formatBytes(totalSize)}</span>}
<input
ref={fileInputRef}
type="file"
multiple
hidden
onChange={(event) => void pickFiles(event.target.files)}
/>
</div>
<InlineError message={error} />
</div>
</Modal>
);
}