fix: правильная конвертация HTML→text для цитирования

Проблема: htmlToText в рендерере удалял только теги, но оставлял контент
<style> и <script> блоков — CSS-правила и JS попадали в цитату.

Решение: конвертация перенесена в main-процесс (imap.provider.ts).
htmlToPlainText() сначала вырезает <style>/<script> целиком, потом
разворачивает блочные элементы в переносы строк и снимает остальные теги.
fetchMessageBody() использует результат как fallback когда email не имеет
text/plain части — MessageBody.text всегда заполнен.

В рендерере htmlToText удалён, quoteBody() теперь просто читает body.text.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Aero Mail Dev 2026-04-17 03:12:21 +00:00
parent 63c0c16c03
commit 8afce5f202
2 changed files with 36 additions and 22 deletions

View file

@ -210,10 +210,14 @@ export class ImapProvider implements IEmailProvider {
? 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
@ -615,6 +619,33 @@ export class ImapProvider implements IEmailProvider {
}
}
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

@ -4,31 +4,14 @@ import type { MessageEnvelope, MessageBody } from '@shared/types/message'
import { useAccountsStore } from './accounts.store'
import { useIpc } from '../composables/useIpc'
function htmlToText(html: string): string {
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/div>/gi, '\n')
.replace(/<\/li>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/\n{3,}/g, '\n\n')
.trim()
}
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 rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '')
const lines = rawText
? rawText.split('\n').map((l) => `> ${l}`).join('\n')
// body.text всегда заполнен на main-процессе (fallback из HTML при отсутствии text/plain части)
const lines = body?.text
? body.text.split('\n').map((l) => `> ${l}`).join('\n')
: ''
return `\n\n--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}`
}