Исправлены редактор письма и получатели, добавлен просмотр картинок

This commit is contained in:
r.rasputin 2026-11-16 11:04:40 +07:00
parent 213868819b
commit ceb1c3a1ef
9 changed files with 248 additions and 49 deletions

View file

@ -0,0 +1,28 @@
import type { ImapCredentials } from '../../shared/types/account'
export function formatSmtpError(error: unknown, credentials: ImapCredentials): string {
const message: string = error instanceof Error ? error.message : String(error)
const host: string = credentials.smtpHost ?? credentials.host.replace(/^imap\./i, 'smtp.')
const port: number = credentials.smtpPort ?? 587
const secure: boolean = credentials.smtpSecure ?? port === 465
const mode: string = secure ? 'SSL/TLS' : 'STARTTLS'
const normalized: string = message.toLowerCase()
let hint: string = ''
if (normalized.includes('wrong version number') || normalized.includes('unknown protocol')) {
hint = 'Проверьте SMTP-порт и режим шифрования: обычно 465 — SSL/TLS, 587 — STARTTLS (переключатель SSL/TLS выключен).'
} else if (normalized.includes('certificate') || normalized.includes('self signed')) {
hint = 'Не удалось проверить сертификат SMTP-сервера. Проверьте имя сервера и доверие к сертификату. Для корпоративного сервера с самоподписанным сертификатом есть отдельная настройка аккаунта.'
} else if (normalized.includes('legacy renegotiation')) {
hint = 'SMTP-сервер использует устаревшее согласование TLS. Требуется обновление TLS на сервере или адрес другого SMTP-сервера у администратора.'
} else if (normalized.includes('ssl') || normalized.includes('tls')) {
hint = 'Не удалось установить защищённое SMTP-соединение. Проверьте порт, режим шифрования и настройки TLS сервера.'
}
return [`SMTP ${host}:${port} (${mode})`, hint, message].filter(Boolean).join('\n')
}
export class SmtpSendError extends Error {
constructor(error: unknown, credentials: ImapCredentials) {
super(formatSmtpError(error, credentials), { cause: error })
this.name = 'SmtpSendError'
}
}

View file

@ -1,3 +1,5 @@
import { getAccountEmail } from '@shared/utils/account-email'
import { SmtpSendError } from '../lib/smtp-error'
import { buildComposeAttachments } from '../lib/compose-attachments'
import { ImapFlow } from 'imapflow'
import { simpleParser } from 'mailparser'
@ -407,9 +409,7 @@ export class ImapProvider implements IEmailProvider {
})
// Если email хранится без домена (только логин) — достраиваем из IMAP-хоста
const emailAddress = this.config.email.includes('@')
? this.config.email
: `${this.config.email}@${creds.host.replace(/^[^.]+\./, '')}`
const emailAddress = getAccountEmail(this.config)
// Имя отправителя: await-им промис из connect() — гарантирует что имя готово
const senderName = await this.senderNamePromise
@ -440,6 +440,8 @@ export class ImapProvider implements IEmailProvider {
inReplyTo: compose.inReplyTo,
references: compose.references,
attachments: buildComposeAttachments(compose)
}).catch((error: unknown): never => {
throw new SmtpSendError(error, creds)
})
// Сохраняем в папку Sent (best-effort)

View file

@ -1,6 +1,7 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { onMounted, ref, watch } from 'vue'
import DOMPurify from 'dompurify'
import ImagePreviewDialog from './ImagePreviewDialog.vue'
import type { ComposeInlineImage } from '@shared/types/message'
interface EditorContent {
@ -9,10 +10,28 @@ interface EditorContent {
images: ComposeInlineImage[]
}
defineOptions({ inheritAttrs: false })
const props = defineProps<{ initialText: string; placeholder: string }>()
const emit = defineEmits<{ busy: [value: boolean]; error: [message: string] }>()
const editor = ref<HTMLDivElement | null>(null)
const pending = ref<number>(0)
const previewSource = ref<string | null>(null)
function openPreview(event: MouseEvent): void {
if (!(event.target instanceof HTMLImageElement)) return
event.preventDefault()
previewSource.value = event.target.src
}
function closePreview(): void {
previewSource.value = null
focus()
}
onMounted((): void => {
if (editor.value) editor.value.innerText = props.initialText
})
watch(() => props.initialText, (text: string): void => {
if (editor.value) editor.value.innerText = text
@ -38,7 +57,7 @@ function readContent(): EditorContent {
const cid: string = `${crypto.randomUUID()}@aero-mail`
images.push({ cid, filename: `image-${images.length + 1}.${match[1].split('/')[1]}`, contentType: match[1], base64: match[2] })
image.setAttribute('src', `cid:${cid}`)
image.setAttribute('style', 'max-width:100%;height:auto')
image.setAttribute('style', 'max-width:180px;max-height:120px;width:auto;height:auto;vertical-align:middle;margin:4px')
}
return { text: editor.value?.innerText ?? '', html: images.length ? `<div style="white-space:pre-wrap">${root.innerHTML}</div>` : undefined, images }
}
@ -58,23 +77,38 @@ async function onPaste(event: ClipboardEvent): Promise<void> {
.filter((item: DataTransferItem): boolean => /^image\/(png|jpeg|gif|webp|bmp)$/.test(item.type))
.map((item: DataTransferItem): File | null => item.getAsFile())
.filter((file: File | null): file is File => file !== null)
if (!files.length) return
event.preventDefault()
if (!files.length) {
document.execCommand('insertText', false, event.clipboardData?.getData('text/plain') ?? '')
return
}
const selection: Selection | null = window.getSelection()
const range: Range | undefined = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined
pending.value += 1
emit('busy', true)
try {
const sources: string[] = await Promise.all(files.map(readImage))
const target: HTMLDivElement | null = editor.value
if (!target) return
focus()
if (range && editor.value?.contains(range.commonAncestorContainer)) {
selection?.removeAllRanges()
selection?.addRange(range)
const insertion: Range = range && target.contains(range.commonAncestorContainer)
? range : document.createRange()
if (insertion !== range) {
insertion.selectNodeContents(target)
insertion.collapse(false)
}
document.execCommand('insertHTML', false, sources.map((source: string): string => `<img src="${source}" alt="Картинка"><br>`).join(''))
const fragment: DocumentFragment = document.createDocumentFragment()
for (const source of sources) {
const image: HTMLImageElement = document.createElement('img')
image.src = source
image.alt = 'Картинка'
image.title = 'Открыть полное изображение'
fragment.append(image)
}
const last: ChildNode | null = fragment.lastChild
insertion.deleteContents()
insertion.insertNode(fragment)
if (last) insertion.setStartAfter(last)
insertion.collapse(true)
selection?.removeAllRanges()
selection?.addRange(insertion)
} catch (error: unknown) {
emit('error', error instanceof Error ? error.message : 'Не удалось вставить картинку')
} finally {
@ -89,17 +123,30 @@ defineExpose({ focus, readContent })
<template>
<div
ref="editor"
:contenteditable="pending === 0"
v-bind="$attrs"
contenteditable="true"
:aria-busy="pending > 0"
role="textbox"
aria-multiline="true"
:aria-label="placeholder"
:data-placeholder="placeholder"
@paste="onPaste"
@click="openPreview"
/>
<ImagePreviewDialog v-if="previewSource" :source="previewSource" @close="closePreview" />
</template>
<style scoped>
[contenteditable] { white-space: pre-wrap; overflow-wrap: anywhere; }
[contenteditable]:empty::before { content: attr(data-placeholder); pointer-events: none; }
[contenteditable] :deep(img) { max-width: 100%; height: auto; }
[contenteditable] :deep(img) {
display: inline-block;
max-width: min(180px, 100%);
max-height: 120px;
width: auto;
height: auto;
vertical-align: middle;
margin: 4px;
cursor: zoom-in;
}
</style>

View file

@ -0,0 +1,87 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
const props = defineProps<{ source: string }>()
const emit = defineEmits<{ close: [] }>()
const dialog = ref<HTMLDialogElement | null>(null)
const isActualSize = ref<boolean>(false)
onMounted((): void => {
dialog.value?.showModal()
})
</script>
<template>
<Teleport to="body">
<dialog
ref="dialog"
class="image-preview"
aria-label="Просмотр изображения"
@click.self="emit('close')"
@cancel.prevent="emit('close')"
@keydown.stop
>
<div class="preview-panel">
<div class="preview-toolbar">
<button type="button" @click="isActualSize = !isActualSize">
{{ isActualSize ? 'Вписать в окно' : 'Исходный размер' }}
</button>
<button type="button" aria-label="Закрыть просмотр" @click="emit('close')">Закрыть</button>
</div>
<div class="preview-content" :class="{ 'actual-size': isActualSize }">
<img :src="props.source" alt="Полное изображение" />
</div>
</div>
</dialog>
</Teleport>
</template>
<style scoped>
.image-preview {
position: fixed;
inset: 0;
width: 100vw;
max-width: none;
height: 100vh;
max-height: none;
margin: 0;
padding: 24px;
border: none;
background: transparent;
color: var(--text-primary);
}
.image-preview::backdrop { background: rgba(0, 0, 0, 0.8); }
.preview-panel {
display: flex;
flex-direction: column;
width: fit-content;
max-width: 100%;
max-height: 100%;
margin: auto;
border-radius: 12px;
overflow: hidden;
background: var(--bg-primary, #19191e);
}
.preview-toolbar {
display: flex;
justify-content: flex-end;
gap: 12px;
padding: 10px;
}
.preview-toolbar button {
padding: 6px 12px;
color: inherit;
background: transparent;
border: 1px solid currentColor;
border-radius: 6px;
cursor: pointer;
}
.preview-content { min-height: 0; overflow: auto; }
.preview-content img {
display: block;
max-width: calc(100vw - 48px);
max-height: calc(100vh - 110px);
object-fit: contain;
}
.actual-size img { max-width: none; max-height: none; }
</style>

View file

@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed, ref, watch, onUnmounted } from 'vue'
import ImagePreviewDialog from '../ImagePreviewDialog.vue'
import type { MessageBody } from '@shared/types/message'
const props = defineProps<{
@ -7,6 +8,27 @@ const props = defineProps<{
}>()
const iframeRef = ref<HTMLIFrameElement | null>(null)
const previewSource = ref<string | null>(null)
let imageDocument: Document | null = null
function openImagePreview(event: MouseEvent): void {
const images: HTMLImageElement[] = Array.from(imageDocument?.querySelectorAll('img') ?? [])
const image: HTMLImageElement | undefined = images.find((candidate: HTMLImageElement): boolean => candidate === event.target)
if (!image?.src) return
event.preventDefault()
event.stopPropagation()
previewSource.value = image.currentSrc || image.src
}
function closeImagePreview(): void {
previewSource.value = null
iframeRef.value?.focus()
}
function detachImagePreview(): void {
imageDocument?.removeEventListener('click', openImagePreview, true)
imageDocument = null
}
// ── Исправление цветов HTML-писем (после загрузки iframe) ─
// postProcessHtml на DOMParser не видит CSS-классы.
@ -90,7 +112,7 @@ const processedHtml = computed(() => {
}
a { color: #a8e600; text-decoration: none; }
a:hover { text-decoration: underline; }
img { max-width: 100%; height: auto; border-radius: 8px; }
img { max-width: 100%; height: auto; border-radius: 8px; cursor: zoom-in; }
table { max-width: 100%; border-collapse: collapse; }
hr {
border: none;
@ -211,6 +233,9 @@ function updateGlowPosition(): void {
const resizeObserver = new ResizeObserver(updateGlowPosition)
function onIframeLoad(): void {
detachImagePreview()
imageDocument = iframeRef.value?.contentDocument ?? null
imageDocument?.addEventListener('click', openImagePreview, true)
updateGlowPosition()
if (iframeRef.value) resizeObserver.observe(iframeRef.value)
fixIframeColors()
@ -239,9 +264,14 @@ function onIframeLoad(): void {
clearContentGlow()
}
watch(() => props.body, () => clearContentGlow())
watch(() => props.body, (): void => {
previewSource.value = null
detachImagePreview()
clearContentGlow()
})
onUnmounted(() => {
detachImagePreview()
clearContentGlow()
resizeObserver.disconnect()
})
@ -257,7 +287,8 @@ onUnmounted(() => {
class="body-frame"
@load="onIframeLoad"
/>
<div v-else class="no-body">
<ImagePreviewDialog v-if="previewSource" :source="previewSource" @close="closeImagePreview" />
<div v-if="!srcdoc" class="no-body">
<span>Содержимое письма недоступно</span>
</div>
</div>

View file

@ -1,4 +1,6 @@
import { defineStore } from 'pinia'
import { getAccountEmail } from '@shared/utils/account-email'
import { excludeOwnAddress } from '../utils/reply-recipients'
import type { ComposeSession } from '@shared/types/message'
import type { MessageEnvelope, MessageBody } from '@shared/types/message'
import { useAccountsStore } from './accounts.store'
@ -78,7 +80,7 @@ export const useComposeStore = defineStore('compose', () => {
if (!acc) return null
return {
accountId: acc.id,
accountEmail: acc.email,
accountEmail: getAccountEmail(acc),
accountLabel: acc.label ?? acc.email
}
}
@ -99,11 +101,9 @@ export const useComposeStore = defineStore('compose', () => {
const acc = getAccountSession()
if (!acc) return
const to = replyAll
? [envelope.from.email, ...envelope.to.map((a) => a.email)].filter(
(e) => e !== acc.accountEmail
)
? excludeOwnAddress([envelope.from.email, ...envelope.to.map((a) => a.email)], acc.accountEmail)
: [envelope.from.email]
const cc = replyAll ? envelope.cc.map((a) => a.email) : []
const cc = replyAll ? excludeOwnAddress(envelope.cc.map((a) => a.email), acc.accountEmail) : []
const session: ComposeSession = {
...acc,
mode: replyAll ? 'replyAll' : 'reply',

View file

@ -0,0 +1,4 @@
export function excludeOwnAddress(addresses: string[], ownEmail: string): string[] {
const normalizedEmail: string = ownEmail.trim().toLowerCase()
return addresses.filter((address: string): boolean => address.trim().toLowerCase() !== normalizedEmail)
}

View file

@ -287,6 +287,10 @@ async function handleSend(): Promise<void> {
}
}
function closeCompose(): void {
window.close()
}
// ── Keyboard ──────────────────────────────────────────────
function onGlobalKeydown(e: KeyboardEvent): void {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); handleSend() }
@ -488,6 +492,8 @@ const totalAttachSize = computed(() =>
</div>
</Transition>
<div v-if="sendError" class="send-error" role="alert">{{ sendError }}</div>
<!-- ── Footer ─────────────────────────────────────── -->
<div class="compose-footer">
<!-- Attach button -->
@ -502,15 +508,10 @@ const totalAttachSize = computed(() =>
<div class="footer-spacer" />
<!-- Error -->
<Transition name="error">
<span v-if="sendError" class="send-error">{{ sendError }}</span>
</Transition>
<!-- Actions -->
<div class="footer-actions">
<span class="shortcut-hint">Ctrl+Enter</span>
<button class="btn-cancel" @click="() => window.close()">Отмена</button>
<button class="btn-cancel" @click="closeCompose">Отмена</button>
<button class="btn-send" :disabled="sending || readingClipboard" @click="handleSend">
<span v-if="sending" class="spinner-sm" />
<AppIcon v-else name="send" :size="13" />
@ -751,7 +752,7 @@ const totalAttachSize = computed(() =>
overflow-y: auto;
}
.compose-body {
.body-area :deep(.compose-body) {
width: 100%;
min-height: 120px;
background: none;
@ -771,7 +772,7 @@ const totalAttachSize = computed(() =>
flex-shrink: 0;
}
.compose-body:empty::before {
.body-area :deep(.compose-body:empty::before) {
color: rgba(255, 255, 255, 0.15);
}
@ -1102,22 +1103,13 @@ const totalAttachSize = computed(() =>
border: 1px solid rgba(255, 60, 60, 0.22);
border-radius: 7px;
padding: 4px 10px;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex-shrink: 1;
}
.error-enter-active,
.error-leave-active {
transition: opacity 160ms ease, transform 160ms ease, max-width 200ms ease;
}
.error-enter-from,
.error-leave-to {
opacity: 0;
transform: translateX(6px);
max-width: 0;
margin: 8px 18px;
max-height: 150px;
overflow-y: auto;
overflow-wrap: anywhere;
white-space: pre-wrap;
user-select: text;
flex-shrink: 0;
}
.footer-actions {
@ -1327,14 +1319,14 @@ html[data-design='material3'] .field-toggle:hover {
}
/* ── Тело письма — body-large согласно контракту ──────────────────────── */
html[data-design='material3'] .compose-body {
:global(html[data-design='material3']) .body-area :deep(.compose-body) {
font-size: var(--md-sys-typescale-body-large-size);
line-height: var(--md-sys-typescale-body-large-line);
font-weight: var(--md-sys-typescale-body-large-weight);
letter-spacing: var(--md-sys-typescale-body-large-tracking);
}
html[data-design='material3'] .compose-body:empty::before {
:global(html[data-design='material3']) .body-area :deep(.compose-body:empty::before) {
color: color-mix(in srgb, var(--md-sys-color-on-surface-variant) 50%, transparent);
}

View file

@ -0,0 +1,8 @@
import type { AccountConfig } from '../types/account'
export function getAccountEmail(account: Pick<AccountConfig, 'email' | 'credentials'>): string {
const email: string = account.email.trim()
if (email.includes('@')) return email
const domain: string = account.credentials.host.replace(/^[^.]+\./, '')
return `${email}@${domain}`
}