Merge branch 'feature/fix-reply-quoting'

Исправление цитирования писем при ответе/пересылке:
- HTML-письма цитируются и отправляются как multipart/alternative
- Имя отправителя берётся из Sent-папки, а не из настроек аккаунта
- Редизайн окна compose: отдельная зона для ответа + collapsible iframe с оригиналом
- Исправлен баг с References header (spread строки → символы)
This commit is contained in:
Aero Mail Dev 2026-04-17 05:34:21 +00:00
commit 3c9c4344bc
5 changed files with 386 additions and 639 deletions

View file

@ -37,6 +37,8 @@ export class ImapProvider implements IEmailProvider {
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
private notifiedUids = new Map<string, number>()
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
// Промис с именем отправителя из Sent-папки; await-ится в sendMessage()
private senderNamePromise: Promise<string | null> = Promise.resolve(null)
constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials
@ -58,6 +60,8 @@ export class ImapProvider implements IEmailProvider {
)
await Promise.race([this.client.connect(), timeout])
this.connected = true
// Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке
this.senderNamePromise = this.fetchSenderName().catch(() => null)
}
async disconnect(): Promise<void> {
@ -179,7 +183,7 @@ export class ImapProvider implements IEmailProvider {
// imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download?.content) {
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
return { id: messageId, html: null, text: null, references: null, inlineImages: [], attachments: [] }
}
const parsed = await simpleParser(download.content)
@ -204,10 +208,21 @@ export class ImapProvider implements IEmailProvider {
}
}
// References header: mailparser returns string[] — join to space-separated string
const refsArray = (parsed as unknown as { references?: string | string[] }).references
const references = Array.isArray(refsArray)
? refsArray.join(' ')
: (typeof refsArray === 'string' ? refsArray : null)
const sanitizedHtml = parsed.html ? sanitizeHtml(parsed.html) : null
// Если text/plain части нет — деривируем из HTML (правильно: style/script уже отфильтрованы)
const text = parsed.text ?? (parsed.html ? this.htmlToPlainText(parsed.html) : null)
return {
id: messageId,
html: parsed.html ? sanitizeHtml(parsed.html) : null,
text: parsed.text ?? null,
html: sanitizedHtml,
text,
references,
inlineImages,
attachments
}
@ -288,10 +303,21 @@ export class ImapProvider implements IEmailProvider {
? this.config.email
: `${this.config.email}@${creds.host.replace(/^[^.]+\./, '')}`
const from = this.config.label
? { name: this.config.label, address: emailAddress }
// Имя отправителя: await-им промис из connect() — гарантирует что имя готово
const senderName = await this.senderNamePromise
const displayName = senderName ?? this.config.label
const from = displayName
? { name: displayName, address: emailAddress }
: emailAddress
// Собираем text + html из отдельных частей
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = compose.htmlBody
? ImapProvider.textToHtml(compose.body) + compose.htmlBody
: undefined
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
smtpHost, smtpPort, smtpSecure, from, compose.to)
@ -301,7 +327,8 @@ export class ImapProvider implements IEmailProvider {
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: compose.body,
text: fullText,
html: fullHtml,
inReplyTo: compose.inReplyTo,
references: compose.references,
attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? []
@ -343,13 +370,21 @@ export class ImapProvider implements IEmailProvider {
): Promise<Buffer | null> {
try {
const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix' })
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = compose.htmlBody
? ImapProvider.textToHtml(compose.body) + compose.htmlBody
: undefined
const mail = await transporter.sendMail({
from,
to: compose.to.join(', '),
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: compose.body,
text: fullText,
html: fullHtml,
messageId,
inReplyTo: compose.inReplyTo,
references: compose.references,
@ -608,6 +643,81 @@ export class ImapProvider implements IEmailProvider {
}
}
/**
* Конвертирует plain text в минимальный HTML (параграфы + переносы строк).
*/
private static textToHtml(text: string): string {
if (!text) return ''
const escaped = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim())
if (paragraphs.length === 0) return '<p></p>'
return paragraphs
.map((p) => `<p>${p.replace(/\n/g, '<br>')}</p>`)
.join('\n')
}
/**
* Ищет имя отправителя в последнем письме папки Sent.
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.
*/
private async fetchSenderName(): Promise<string | null> {
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const sentPath = this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent)
if (!sentPath) return null
const status = await this.client.status(sentPath, { messages: true }) as { messages?: number } | null
const total = status?.messages ?? 0
if (total === 0) return null
const lock = await this.client.getMailboxLock(sentPath)
try {
let name: string | null = null
// Берём только самое последнее письмо
for await (const msg of this.client.fetch(`${total}:${total}`, { envelope: true })) {
const fromList = (msg as { envelope?: { from?: Array<{ name?: string }> } }).envelope?.from
const candidate = fromList?.[0]?.name?.trim()
if (candidate) { name = candidate; break }
}
return name
} finally {
lock.release()
}
} catch {
return null
}
}
private htmlToPlainText(html: string): string {
return html
// Убираем целиком блоки <style> и <script> вместе с содержимым
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
// Блочные элементы → переносы строк
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/div>/gi, '\n')
.replace(/<\/li>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<\/h[1-6]>/gi, '\n\n')
// Удаляем все оставшиеся теги
.replace(/<[^>]+>/g, '')
// HTML-сущности
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
// &amp; — последним, чтобы не двойной-декодинг
.replace(/&amp;/g, '&')
// Убираем лишние пустые строки
.replace(/\n{3,}/g, '\n\n')
.trim()
}
private hasAttachments(node?: BodyPart): boolean {
if (!node) return false
if (node.disposition === 'attachment') return true

View file

@ -1,600 +0,0 @@
<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useComposeStore } from '../../stores/compose.store'
import AppIcon from '../AppIcon.vue'
const composeStore = useComposeStore()
// ── Адресные поля (token-input) ───────────────────────────
type Field = 'to' | 'cc' | 'bcc'
const toInput = ref('')
const ccInput = ref('')
const bccInput = ref('')
const showCc = ref(false)
const showBcc = ref(false)
const toInputEl = ref<HTMLInputElement | null>(null)
const bodyEl = ref<HTMLTextAreaElement | null>(null)
watch(() => composeStore.draft, (d) => {
if (!d) return
toInput.value = ''
ccInput.value = ''
bccInput.value = ''
showCc.value = d.cc.length > 0
showBcc.value = d.bcc.length > 0
nextTick(() => {
if (d.mode === 'new') {
toInputEl.value?.focus()
} else {
bodyEl.value?.focus()
// Ставим курсор в начало (перед цитатой)
bodyEl.value?.setSelectionRange(0, 0)
}
})
}, { immediate: true })
function inputModel(field: Field): { value: string; update: (v: string) => void } {
if (field === 'to') return { value: toInput.value, update: (v) => { toInput.value = v } }
if (field === 'cc') return { value: ccInput.value, update: (v) => { ccInput.value = v } }
return { value: bccInput.value, update: (v) => { bccInput.value = v } }
}
function parseEmails(raw: string): string[] {
return raw.split(/[,;\s]+/)
.map((s) => s.trim())
.filter((s) => s.includes('@'))
}
function commitInput(field: Field): void {
if (!composeStore.draft) return
const raw = field === 'to' ? toInput.value : field === 'cc' ? ccInput.value : bccInput.value
const emails = parseEmails(raw)
if (!emails.length) return
composeStore.draft[field] = [...composeStore.draft[field], ...emails]
if (field === 'to') toInput.value = ''
if (field === 'cc') ccInput.value = ''
if (field === 'bcc') bccInput.value = ''
}
function onAddressKeydown(e: KeyboardEvent, field: Field): void {
if (e.key === 'Enter' || e.key === 'Tab' || e.key === ',') {
e.preventDefault()
commitInput(field)
}
if (e.key === 'Backspace') {
const raw = field === 'to' ? toInput.value : field === 'cc' ? ccInput.value : bccInput.value
if (raw === '' && composeStore.draft) {
composeStore.draft[field].pop()
}
}
}
function removeAddr(field: Field, idx: number): void {
composeStore.draft?.[field].splice(idx, 1)
}
function onAddressBlur(field: Field): void {
commitInput(field)
}
// ── Отправка ──────────────────────────────────────────────
async function handleSend(): Promise<void> {
if (!composeStore.draft) return
// Сначала коммитим незаконченный ввод адресов
commitInput('to')
commitInput('cc')
commitInput('bcc')
await nextTick()
await composeStore.send()
}
// ── Keyboard shortcut Ctrl/Cmd+Enter ─────────────────────
function onKeydown(e: KeyboardEvent): void {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault()
handleSend()
}
if (e.key === 'Escape') {
composeStore.close()
}
}
onMounted(() => document.addEventListener('keydown', onKeydown))
onUnmounted(() => document.removeEventListener('keydown', onKeydown))
// ── Title ─────────────────────────────────────────────────
const title = computed(() => {
switch (composeStore.draft?.mode) {
case 'reply': return 'Ответить'
case 'replyAll': return 'Ответить всем'
case 'forward': return 'Переслать'
default: return 'Новое письмо'
}
})
</script>
<template>
<Transition name="compose">
<div v-if="composeStore.isOpen" class="compose-overlay" @mousedown.self="composeStore.close()">
<div class="compose-window" @keydown.stop>
<!-- Header -->
<div class="compose-header">
<span class="compose-title">{{ title }}</span>
<button class="compose-close" @click="composeStore.close()">
<AppIcon name="close" :size="11" />
</button>
</div>
<!-- Fields -->
<div class="compose-fields" v-if="composeStore.draft">
<!-- To -->
<div class="field-row">
<span class="field-label">Кому</span>
<div class="addr-input-wrap">
<span
v-for="(addr, i) in composeStore.draft.to"
:key="i"
class="addr-token"
>
{{ addr }}
<button class="token-remove" @click="removeAddr('to', i)">&times;</button>
</span>
<input
ref="toInputEl"
class="addr-input"
:value="toInput"
placeholder="email@example.com"
@input="toInput = ($event.target as HTMLInputElement).value"
@keydown="onAddressKeydown($event, 'to')"
@blur="onAddressBlur('to')"
/>
</div>
<div class="field-actions">
<button v-if="!showCc" class="toggle-field" @click="showCc = true">Копия</button>
<button v-if="!showBcc" class="toggle-field" @click="showBcc = true">Скрытая</button>
</div>
</div>
<!-- Cc -->
<div v-if="showCc" class="field-row">
<span class="field-label">Копия</span>
<div class="addr-input-wrap">
<span
v-for="(addr, i) in composeStore.draft.cc"
:key="i"
class="addr-token"
>
{{ addr }}
<button class="token-remove" @click="removeAddr('cc', i)">&times;</button>
</span>
<input
class="addr-input"
:value="ccInput"
placeholder="email@example.com"
@input="ccInput = ($event.target as HTMLInputElement).value"
@keydown="onAddressKeydown($event, 'cc')"
@blur="onAddressBlur('cc')"
/>
</div>
</div>
<!-- Bcc -->
<div v-if="showBcc" class="field-row">
<span class="field-label">Скрытая</span>
<div class="addr-input-wrap">
<span
v-for="(addr, i) in composeStore.draft.bcc"
:key="i"
class="addr-token"
>
{{ addr }}
<button class="token-remove" @click="removeAddr('bcc', i)">&times;</button>
</span>
<input
class="addr-input"
:value="bccInput"
placeholder="email@example.com"
@input="bccInput = ($event.target as HTMLInputElement).value"
@keydown="onAddressKeydown($event, 'bcc')"
@blur="onAddressBlur('bcc')"
/>
</div>
</div>
<!-- Subject -->
<div class="field-row">
<span class="field-label">Тема</span>
<input
class="subject-input"
v-model="composeStore.draft.subject"
placeholder="Тема письма"
/>
</div>
</div>
<!-- Divider -->
<div class="compose-divider" />
<!-- Body -->
<textarea
ref="bodyEl"
class="compose-body"
v-model="composeStore.draft!.body"
placeholder="Напишите сообщение..."
/>
<!-- Footer -->
<div class="compose-footer">
<div v-if="composeStore.sendError" class="send-error">
{{ composeStore.sendError }}
</div>
<div class="footer-actions">
<button class="btn-cancel" @click="composeStore.close()">Отмена</button>
<button
class="btn-send"
:disabled="composeStore.sending || !composeStore.draft?.to.length && !toInput"
@click="handleSend"
>
<span v-if="composeStore.sending" class="spinner-sm" />
<span class="send-icon" v-else><AppIcon name="send" :size="13" /></span>
{{ composeStore.sending ? 'Отправка...' : 'Отправить' }}
</button>
</div>
</div>
</div>
</div>
</Transition>
</template>
<style scoped>
/* ── Overlay ─────────────────────────────────────────────── */
.compose-overlay {
position: fixed;
inset: 0;
z-index: 200;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.45);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
/* ── Window ──────────────────────────────────────────────── */
.compose-window {
width: 660px;
max-width: calc(100vw - 48px);
max-height: calc(100vh - 80px);
display: flex;
flex-direction: column;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.13);
background:
linear-gradient(160deg, rgba(255, 255, 255, 0.09) 0%, rgba(255, 255, 255, 0.02) 100%),
rgba(12, 12, 22, 0.92);
backdrop-filter: blur(56px) saturate(2.2);
-webkit-backdrop-filter: blur(56px) saturate(2.2);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.18),
inset 0 0 0 1px rgba(255, 255, 255, 0.04),
0 24px 80px rgba(0, 0, 0, 0.65),
0 8px 24px rgba(0, 0, 0, 0.40);
overflow: hidden;
}
/* ── Header ──────────────────────────────────────────────── */
.compose-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px 12px;
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
flex-shrink: 0;
}
.compose-title {
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: 0.01em;
}
.compose-close {
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
color: var(--text-muted);
transition: background var(--transition-fast), color var(--transition-fast);
}
.compose-close:hover {
background: rgba(255, 255, 255, 0.10);
color: var(--text-primary);
}
/* ── Fields ──────────────────────────────────────────────── */
.compose-fields {
flex-shrink: 0;
padding: 4px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
}
.field-row {
display: flex;
align-items: flex-start;
gap: 0;
padding: 6px 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
min-height: 36px;
}
.field-row:last-child {
border-bottom: none;
}
.field-label {
flex-shrink: 0;
width: 60px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-muted);
padding-top: 8px;
user-select: none;
}
/* ── Address token input ─────────────────────────────────── */
.addr-input-wrap {
flex: 1;
display: flex;
flex-wrap: wrap;
gap: 4px;
align-items: center;
padding: 4px 0;
min-height: 28px;
}
.addr-token {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px 2px 9px;
border-radius: 99px;
font-size: 12px;
color: var(--text-secondary);
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.12);
white-space: nowrap;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
}
.token-remove {
flex-shrink: 0;
font-size: 13px;
line-height: 1;
color: var(--text-muted);
padding: 0 1px;
transition: color var(--transition-fast);
}
.token-remove:hover {
color: var(--danger);
}
.addr-input {
flex: 1;
min-width: 140px;
background: none;
border: none;
outline: none;
color: var(--text-primary);
font-size: 13px;
padding: 3px 0;
caret-color: var(--accent);
}
.addr-input::placeholder {
color: rgba(255, 255, 255, 0.20);
}
.field-actions {
flex-shrink: 0;
display: flex;
gap: 4px;
padding-top: 7px;
}
.toggle-field {
font-size: 11px;
color: var(--text-muted);
padding: 1px 6px;
border-radius: 4px;
transition: color var(--transition-fast), background var(--transition-fast);
}
.toggle-field:hover {
color: var(--text-secondary);
background: rgba(255, 255, 255, 0.06);
}
/* Subject input */
.subject-input {
flex: 1;
background: none;
border: none;
outline: none;
color: var(--text-primary);
font-size: 13px;
font-weight: 500;
padding: 7px 0;
caret-color: var(--accent);
}
.subject-input::placeholder {
color: rgba(255, 255, 255, 0.20);
font-weight: 400;
}
/* ── Divider ─────────────────────────────────────────────── */
.compose-divider {
height: 1px;
background: rgba(255, 255, 255, 0.06);
flex-shrink: 0;
}
/* ── Body ────────────────────────────────────────────────── */
.compose-body {
flex: 1;
background: none;
border: none;
outline: none;
resize: none;
color: var(--text-primary);
font-size: 13px;
line-height: 1.65;
padding: 14px 16px;
min-height: 220px;
caret-color: var(--accent);
font-family: inherit;
}
.compose-body::placeholder {
color: rgba(255, 255, 255, 0.18);
}
/* ── Footer ──────────────────────────────────────────────── */
.compose-footer {
flex-shrink: 0;
padding: 10px 16px 14px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
background: rgba(0, 0, 0, 0.12);
}
.send-error {
font-size: 12px;
color: var(--danger);
margin-bottom: 8px;
padding: 6px 10px;
background: rgba(255, 60, 60, 0.10);
border: 1px solid rgba(255, 60, 60, 0.20);
border-radius: 7px;
}
.footer-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
}
.btn-cancel {
padding: 7px 16px;
border-radius: var(--radius-full);
font-size: 13px;
color: var(--text-muted);
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.09);
transition: background var(--transition-fast), color var(--transition-fast);
}
.btn-cancel:hover {
background: rgba(255, 255, 255, 0.09);
color: var(--text-secondary);
}
.btn-send {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 20px;
border-radius: var(--radius-full);
font-size: 13px;
font-weight: 600;
color: var(--accent-text);
background: linear-gradient(
to bottom,
color-mix(in srgb, var(--accent) 88%, white 12%) 0%,
var(--accent) 100%
);
border: none;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.35),
0 2px 10px color-mix(in srgb, var(--accent) 35%, transparent);
cursor: pointer;
transition:
background var(--transition-fast),
box-shadow var(--transition-fast),
transform var(--transition-fast),
opacity var(--transition-fast);
}
.btn-send:hover:not(:disabled) {
background: linear-gradient(
to bottom,
color-mix(in srgb, var(--accent-hover) 88%, white 12%) 0%,
var(--accent-hover) 100%
);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.40),
0 4px 18px color-mix(in srgb, var(--accent) 45%, transparent);
transform: translateY(-1px);
}
.btn-send:active:not(:disabled) {
transform: translateY(0);
box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.20);
}
.btn-send:disabled {
opacity: 0.45;
cursor: not-allowed;
transform: none;
}
.send-icon {
display: flex;
align-items: center;
}
.spinner-sm {
width: 13px;
height: 13px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.7s linear infinite;
flex-shrink: 0;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* ── Transitions ─────────────────────────────────────────── */
.compose-enter-active {
transition: opacity 180ms ease, transform 220ms cubic-bezier(0.34, 1.1, 0.64, 1);
}
.compose-leave-active {
transition: opacity 140ms ease, transform 160ms ease;
}
.compose-enter-from {
opacity: 0;
transform: scale(0.96) translateY(12px);
}
.compose-leave-to {
opacity: 0;
transform: scale(0.97) translateY(6px);
}
</style>

View file

@ -4,14 +4,69 @@ import type { MessageEnvelope, MessageBody } from '@shared/types/message'
import { useAccountsStore } from './accounts.store'
import { useIpc } from '../composables/useIpc'
/**
* Стриппер HTML → plain text для цитирования.
* Применяется только как fallback когда body.text отсутствует (HTML-only письма
* до перезапуска main-процесса или из старого кеша).
*/
function htmlToText(html: string): string {
return html
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/div>/gi, '\n')
.replace(/<\/li>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<\/h[1-6]>/gi, '\n\n')
.replace(/<[^>]+>/g, '')
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, '&')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function escHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
/** Plain-text цитата оригинала (> строки с атрибуцией). Без ведущих \n\n. */
function quoteBody(envelope: MessageEnvelope, body: MessageBody | null): string {
const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : ''
const from = envelope.from.name
? `${envelope.from.name} <${envelope.from.email}>`
: envelope.from.email
const text = body?.text ?? ''
const lines = text.split('\n').map((l) => `> ${l}`).join('\n')
return `\n\n--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}`
const rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '')
const lines = rawText
? rawText.split('\n').map((l) => `> ${l}`).join('\n')
: ''
return `--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}`
}
/**
* HTML-блокквота оригинала (для рендера в compose + text/html часть).
* Возвращает undefined если оригинал — plain-text (тогда шлём только text/plain).
*/
function quoteBodyHtml(envelope: MessageEnvelope, body: MessageBody | null): string | undefined {
if (!body?.html) return undefined
const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : ''
const from = envelope.from.name
? `${escHtml(envelope.from.name)} &lt;${escHtml(envelope.from.email)}&gt;`
: escHtml(envelope.from.email)
return (
`<div style="font-size:12px;color:#888;margin-bottom:8px">` +
`&#8212; Оригинальное письмо &#8212;<br>` +
`От: ${from}<br>` +
`Дата: ${escHtml(date)}<br>` +
`Тема: ${escHtml(envelope.subject)}` +
`</div>` +
`<blockquote style="margin:0 0 0 .8ex;border-left:3px solid #ccc;padding-left:1ex">` +
body.html +
`</blockquote>`
)
}
export const useComposeStore = defineStore('compose', () => {
@ -30,14 +85,14 @@ export const useComposeStore = defineStore('compose', () => {
function openNew(): void {
const acc = getAccountSession()
if (!acc) return
if (!acc) { console.warn('[compose] no active account'); return }
const session: ComposeSession = {
...acc,
mode: 'new',
to: [], cc: [], bcc: [],
subject: '', body: ''
}
invoke('compose:open', session)
invoke('compose:open', session).catch((e) => console.error('[compose:open]', e))
}
function openReply(envelope: MessageEnvelope, body: MessageBody | null, replyAll = false): void {
@ -56,15 +111,17 @@ export const useComposeStore = defineStore('compose', () => {
cc,
bcc: [],
subject: envelope.subject.startsWith('Re:') ? envelope.subject : `Re: ${envelope.subject}`,
body: quoteBody(envelope, body),
body: '',
quotedText: quoteBody(envelope, body),
htmlBody: quoteBodyHtml(envelope, body),
inReplyTo: envelope.messageId,
references: envelope.messageId
? [envelope.inReplyTo, envelope.messageId].filter(Boolean).join(' ')
? [body?.references ?? envelope.inReplyTo, envelope.messageId].filter(Boolean).join(' ').trim() || undefined
: undefined,
replyToMessageId: envelope.id,
replyToFolderId: envelope.folderId
}
invoke('compose:open', session)
invoke('compose:open', session).catch((e) => console.error('[compose:open]', e))
}
function openForward(envelope: MessageEnvelope, body: MessageBody | null): void {
@ -75,9 +132,11 @@ export const useComposeStore = defineStore('compose', () => {
mode: 'forward',
to: [], cc: [], bcc: [],
subject: envelope.subject.startsWith('Fwd:') ? envelope.subject : `Fwd: ${envelope.subject}`,
body: quoteBody(envelope, body)
body: '',
quotedText: quoteBody(envelope, body),
htmlBody: quoteBodyHtml(envelope, body)
}
invoke('compose:open', session)
invoke('compose:open', session).catch((e) => console.error('[compose:open]', e))
}
return { openNew, openReply, openForward }

View file

@ -15,6 +15,8 @@ const cc = ref<string[]>([])
const bcc = ref<string[]>([])
const subject = ref('')
const body = ref('')
const quotedText = ref('')
const htmlBody = ref('')
const showCc = ref(false)
const showBcc = ref(false)
@ -27,11 +29,85 @@ const ccInputEl = ref<HTMLInputElement | null>(null)
const bccInputEl = ref<HTMLInputElement | null>(null)
const bodyEl = ref<HTMLTextAreaElement | null>(null)
// ── Quote ─────────────────────────────────────────────────
const quoteExpanded = ref(true)
const hasQuote = computed(() => !!(htmlBody.value || quotedText.value))
const isReplyOrForward = computed(() => {
const m = session.value?.mode
return m === 'reply' || m === 'replyAll' || m === 'forward'
})
/** srcdoc для iframe с оригинальным HTML-письмом */
const quoteSrcdoc = computed(() => {
if (htmlBody.value) {
return `<!DOCTYPE html>
<html><head><meta charset="utf-8">
<style>
* { box-sizing: border-box; }
body {
background: transparent;
color: rgba(255,255,255,0.88);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 13px;
line-height: 1.6;
padding: 14px 18px;
margin: 0;
word-wrap: break-word;
overflow-wrap: break-word;
}
a { color: #a8e600; text-decoration: none; }
a:hover { text-decoration: underline; }
img { max-width: 100%; height: auto; border-radius: 6px; }
table { max-width: 100%; border-collapse: collapse; }
blockquote {
border-left: 3px solid rgba(255,255,255,0.15);
margin: 8px 0;
padding: 4px 12px;
color: rgba(255,255,255,0.55);
}
hr { border: none; border-top: 1px solid rgba(255,255,255,0.08); margin: 12px 0; }
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.13); border-radius: 9999px; }
</style>
</head><body>${htmlBody.value}</body></html>`
}
if (quotedText.value) {
const escaped = quotedText.value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\n/g, '<br>')
return `<!DOCTYPE html>
<html><head><meta charset="utf-8">
<style>
body {
background: transparent;
color: rgba(255,255,255,0.55);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 12px;
line-height: 1.6;
padding: 14px 18px;
margin: 0;
white-space: pre-wrap;
word-wrap: break-word;
}
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.13); border-radius: 9999px; }
</style>
</head><body>${escaped}</body></html>`
}
return ''
})
// ── Attachments ───────────────────────────────────────────
interface LocalAttachment extends ComposeAttachment { id: string }
const attachments = ref<LocalAttachment[]>([])
const isDragging = ref(false)
let dragCounter = 0 // track nested dragenter/dragleave
let dragCounter = 0
// ── Status ────────────────────────────────────────────────
const sending = ref(false)
@ -41,21 +117,19 @@ const sendError = ref('')
onMounted(async () => {
const data = await invoke('compose:getData')
if (!data) return
session.value = data
to.value = [...(data.to ?? [])]
cc.value = [...(data.cc ?? [])]
bcc.value = [...(data.bcc ?? [])]
subject.value = data.subject ?? ''
body.value = data.body ?? ''
showCc.value = cc.value.length > 0
showBcc.value = bcc.value.length > 0
session.value = data
to.value = [...(data.to ?? [])]
cc.value = [...(data.cc ?? [])]
bcc.value = [...(data.bcc ?? [])]
subject.value = data.subject ?? ''
body.value = data.body ?? ''
quotedText.value = data.quotedText ?? ''
htmlBody.value = data.htmlBody ?? ''
showCc.value = cc.value.length > 0
showBcc.value = bcc.value.length > 0
nextTick(() => {
if (data.mode === 'new') toInputEl.value?.focus()
else {
bodyEl.value?.focus()
bodyEl.value?.setSelectionRange(0, 0)
}
bodyEl.value?.focus()
})
})
@ -186,9 +260,11 @@ async function handleSend(): Promise<void> {
bcc: [...bcc.value],
subject: subject.value,
body: body.value,
quotedText: quotedText.value || undefined,
htmlBody: htmlBody.value || undefined,
attachments: attachments.value.map(({ path, filename, size }) => ({ path, filename, size })),
inReplyTo: sess.inReplyTo,
references: sess.references ? [...sess.references] : undefined,
references: sess.references || undefined,
replyToMessageId: sess.replyToMessageId,
replyToFolderId: sess.replyToFolderId
}
@ -240,7 +316,7 @@ const totalAttachSize = computed(() =>
</div>
<div v-if="session" class="header-from">
<span class="from-dot" />
<span class="from-label">{{ session.accountLabel || session.accountEmail }}</span>
<span class="from-label">{{ session.accountEmail }}</span>
</div>
</div>
@ -292,7 +368,7 @@ const totalAttachSize = computed(() =>
@blur="commitInput('cc')"
/>
</div>
<button class="field-toggle close-field" @click="showCc = false; cc = []">✕</button>
<button class="field-toggle close-field" @click="showCc = false; cc = []">&#10005;</button>
</div>
</template>
@ -317,7 +393,7 @@ const totalAttachSize = computed(() =>
@blur="commitInput('bcc')"
/>
</div>
<button class="field-toggle close-field" @click="showBcc = false; bcc = []">✕</button>
<button class="field-toggle close-field" @click="showBcc = false; bcc = []">&#10005;</button>
</div>
</template>
@ -340,9 +416,31 @@ const totalAttachSize = computed(() =>
ref="bodyEl"
class="compose-body"
v-model="body"
placeholder="Напишите сообщение…"
:placeholder="isReplyOrForward ? 'Напишите ответ…' : 'Напишите сообщение…'"
/>
<!-- ── Quote section (reply/forward) ─────────────── -->
<template v-if="hasQuote">
<button class="quote-toggle" @click="quoteExpanded = !quoteExpanded">
<span class="quote-toggle-line" />
<span class="quote-toggle-label">
<AppIcon name="chevron-right" :size="10" :style="{ transform: quoteExpanded ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s' }" />
Оригинальное письмо
</span>
<span class="quote-toggle-line" />
</button>
<Transition name="quote">
<div v-if="quoteExpanded" class="quote-frame-wrap">
<iframe
:srcdoc="quoteSrcdoc"
class="quote-frame"
sandbox="allow-same-origin"
/>
</div>
</Transition>
</template>
<!-- Drag-drop overlay -->
<Transition name="drag">
<div v-if="isDragging" class="drag-overlay">
@ -447,6 +545,7 @@ const totalAttachSize = computed(() =>
inset 0 1px 0 rgba(255, 255, 255, 0.12),
0 1px 0 rgba(0, 0, 0, 0.25);
user-select: none;
-webkit-app-region: drag;
}
.header-mode {
@ -639,11 +738,14 @@ const totalAttachSize = computed(() =>
position: relative;
min-height: 0;
margin: 8px 0 0;
display: flex;
flex-direction: column;
overflow-y: auto;
}
.compose-body {
width: 100%;
height: 100%;
min-height: 120px;
background: none;
border: none;
outline: none;
@ -651,19 +753,92 @@ const totalAttachSize = computed(() =>
color: var(--text-primary);
font-size: 13px;
line-height: 1.7;
padding: 12px 18px 12px;
padding: 12px 18px;
caret-color: var(--accent);
font-family: inherit;
box-shadow: none;
backdrop-filter: none;
-webkit-backdrop-filter: none;
user-select: text;
flex-shrink: 0;
}
.compose-body::placeholder {
color: rgba(255, 255, 255, 0.15);
}
/* ── Quote section ───────────────────────────────────────── */
.quote-toggle {
display: flex;
align-items: center;
gap: 10px;
padding: 4px 18px;
cursor: pointer;
user-select: none;
flex-shrink: 0;
}
.quote-toggle-line {
flex: 1;
height: 1px;
background: rgba(255, 255, 255, 0.07);
}
.quote-toggle-label {
display: flex;
align-items: center;
gap: 5px;
font-size: 11px;
font-weight: 500;
color: var(--text-muted);
opacity: 0.6;
white-space: nowrap;
transition: opacity var(--transition-fast), color var(--transition-fast);
}
.quote-toggle:hover .quote-toggle-label {
opacity: 1;
color: var(--text-secondary);
}
.quote-frame-wrap {
flex: 1;
min-height: 120px;
margin: 0 12px 8px;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(10, 10, 16, 0.5);
overflow: hidden;
}
.quote-frame {
width: 100%;
height: 100%;
min-height: 120px;
border: none;
background: transparent;
display: block;
}
.quote-enter-active {
transition: opacity 180ms ease, max-height 250ms ease;
max-height: 600px;
overflow: hidden;
}
.quote-leave-active {
transition: opacity 120ms ease, max-height 200ms ease;
max-height: 600px;
overflow: hidden;
}
.quote-enter-from {
opacity: 0;
max-height: 0;
}
.quote-leave-to {
opacity: 0;
max-height: 0;
}
/* ── Drag overlay ────────────────────────────────────────── */
.drag-overlay {
position: absolute;

View file

@ -42,6 +42,7 @@ export interface MessageBody {
id: string
html: string | null
text: string | null
references: string | null // References header (цепочка Message-ID для треда)
inlineImages: InlineImage[]
attachments: Attachment[]
}
@ -57,7 +58,9 @@ export interface ComposeData {
cc: string[]
bcc: string[]
subject: string
body: string // plain text
body: string // Текст пользователя (без цитаты)
quotedText?: string // Plain-text цитата оригинала (> строки с атрибуцией)
htmlBody?: string // HTML-блокквота оригинала (для рендера в compose + text/html часть)
attachments?: ComposeAttachment[]
inReplyTo?: string // Message-ID оригинала (для ответа)
references?: string // References header