Compare commits

..

No commits in common. "42e901c25baf89e1863f0b27c6fe205c1a9722a8" and "a285f78d1a474a0cf7195d7933a32df43623d699" have entirely different histories.

9 changed files with 49 additions and 248 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,8 +0,0 @@
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}`
}