Добавлена вставка картинок из буфера в письмо
All checks were successful
Release / release (push) Successful in 3m7s
All checks were successful
Release / release (push) Successful in 3m7s
This commit is contained in:
parent
eb220a85ba
commit
9378455b61
5 changed files with 158 additions and 18 deletions
18
src/main/lib/compose-attachments.ts
Normal file
18
src/main/lib/compose-attachments.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import type { Attachment } from 'nodemailer/lib/mailer'
|
||||
import type { ComposeData } from '../../shared/types/message'
|
||||
|
||||
export function buildComposeAttachments(compose: ComposeData): Attachment[] {
|
||||
return [
|
||||
...(compose.attachments ?? []).map((attachment) => ({
|
||||
path: attachment.path,
|
||||
filename: attachment.filename
|
||||
})),
|
||||
...(compose.inlineImages ?? []).map((image) => ({
|
||||
filename: image.filename,
|
||||
content: Buffer.from(image.base64, 'base64'),
|
||||
contentType: image.contentType,
|
||||
cid: image.cid,
|
||||
contentDisposition: 'inline' as const
|
||||
}))
|
||||
]
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { buildComposeAttachments } from '../lib/compose-attachments'
|
||||
import { ImapFlow } from 'imapflow'
|
||||
import { simpleParser } from 'mailparser'
|
||||
import nodemailer from 'nodemailer'
|
||||
|
|
@ -421,9 +422,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
const fullText = compose.quotedText
|
||||
? compose.body + '\n\n' + compose.quotedText
|
||||
: compose.body
|
||||
const fullHtml = compose.htmlBody
|
||||
? ImapProvider.textToHtml(compose.body) + compose.htmlBody
|
||||
: undefined
|
||||
const fullHtml = ImapProvider.buildComposeHtml(compose)
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
|
||||
|
|
@ -440,7 +439,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
html: fullHtml,
|
||||
inReplyTo: compose.inReplyTo,
|
||||
references: compose.references,
|
||||
attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? []
|
||||
attachments: buildComposeAttachments(compose)
|
||||
})
|
||||
|
||||
// Сохраняем в папку Sent (best-effort)
|
||||
|
|
@ -482,9 +481,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
const fullText = compose.quotedText
|
||||
? compose.body + '\n\n' + compose.quotedText
|
||||
: compose.body
|
||||
const fullHtml = compose.htmlBody
|
||||
? ImapProvider.textToHtml(compose.body) + compose.htmlBody
|
||||
: undefined
|
||||
const fullHtml = ImapProvider.buildComposeHtml(compose)
|
||||
|
||||
const mail = await transporter.sendMail({
|
||||
from,
|
||||
|
|
@ -498,7 +495,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
inReplyTo: compose.inReplyTo,
|
||||
references: compose.references,
|
||||
date: new Date(),
|
||||
attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? []
|
||||
attachments: buildComposeAttachments(compose)
|
||||
})
|
||||
const chunks: Buffer[] = []
|
||||
await new Promise<void>((res, rej) => {
|
||||
|
|
@ -752,9 +749,12 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертирует plain text в минимальный HTML (параграфы + переносы строк).
|
||||
*/
|
||||
private static buildComposeHtml(compose: ComposeData): string | undefined {
|
||||
if (!compose.contentHtml && !compose.htmlBody) return undefined
|
||||
const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '')
|
||||
return (compose.contentHtml ?? ImapProvider.textToHtml(compose.body)) + quote
|
||||
}
|
||||
|
||||
private static textToHtml(text: string): string {
|
||||
if (!text) return ''
|
||||
const escaped = text
|
||||
|
|
|
|||
105
src/renderer/src/components/ComposeEditor.vue
Normal file
105
src/renderer/src/components/ComposeEditor.vue
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import DOMPurify from 'dompurify'
|
||||
import type { ComposeInlineImage } from '@shared/types/message'
|
||||
|
||||
interface EditorContent {
|
||||
text: string
|
||||
html: string | undefined
|
||||
images: ComposeInlineImage[]
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
watch(() => props.initialText, (text: string): void => {
|
||||
if (editor.value) editor.value.innerText = text
|
||||
}, { flush: 'post' })
|
||||
|
||||
function focus(): void {
|
||||
editor.value?.focus()
|
||||
}
|
||||
|
||||
function readContent(): EditorContent {
|
||||
const root: HTMLDivElement = document.createElement('div')
|
||||
root.innerHTML = DOMPurify.sanitize(editor.value?.innerHTML ?? '', {
|
||||
ALLOWED_TAGS: ['div', 'p', 'br', 'img'],
|
||||
ALLOWED_ATTR: ['src', 'alt']
|
||||
})
|
||||
const images: ComposeInlineImage[] = []
|
||||
for (const image of root.querySelectorAll('img')) {
|
||||
const match: RegExpMatchArray | null = image.src.match(/^data:(image\/(?:png|jpeg|gif|webp|bmp));base64,([A-Za-z0-9+/=]+)$/)
|
||||
if (!match) {
|
||||
image.remove()
|
||||
continue
|
||||
}
|
||||
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')
|
||||
}
|
||||
return { text: editor.value?.innerText ?? '', html: images.length ? `<div style="white-space:pre-wrap">${root.innerHTML}</div>` : undefined, images }
|
||||
}
|
||||
|
||||
function readImage(file: File): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader: FileReader = new FileReader()
|
||||
reader.onload = (): void => resolve(String(reader.result))
|
||||
reader.onerror = (): void => reject(reader.error ?? new DOMException('Не удалось прочитать картинку', 'NotReadableError'))
|
||||
reader.onabort = (): void => reject(new DOMException('Чтение картинки отменено', 'AbortError'))
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
async function onPaste(event: ClipboardEvent): Promise<void> {
|
||||
const files: File[] = Array.from(event.clipboardData?.items ?? [])
|
||||
.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)
|
||||
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))
|
||||
focus()
|
||||
if (range && editor.value?.contains(range.commonAncestorContainer)) {
|
||||
selection?.removeAllRanges()
|
||||
selection?.addRange(range)
|
||||
}
|
||||
document.execCommand('insertHTML', false, sources.map((source: string): string => `<img src="${source}" alt="Картинка"><br>`).join(''))
|
||||
} catch (error: unknown) {
|
||||
emit('error', error instanceof Error ? error.message : 'Не удалось вставить картинку')
|
||||
} finally {
|
||||
pending.value -= 1
|
||||
emit('busy', pending.value > 0)
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ focus, readContent })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="editor"
|
||||
:contenteditable="pending === 0"
|
||||
role="textbox"
|
||||
aria-multiline="true"
|
||||
:aria-label="placeholder"
|
||||
:data-placeholder="placeholder"
|
||||
@paste="onPaste"
|
||||
/>
|
||||
</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; }
|
||||
</style>
|
||||
|
|
@ -3,6 +3,7 @@ import { ref, computed, onMounted, onUnmounted, nextTick, toRaw } from 'vue'
|
|||
import type { ComposeSession, ComposeAttachment } from '@shared/types/message'
|
||||
import { useIpc } from '../composables/useIpc'
|
||||
import AppIcon from '../components/AppIcon.vue'
|
||||
import ComposeEditor from '../components/ComposeEditor.vue'
|
||||
|
||||
const { invoke } = useIpc()
|
||||
|
||||
|
|
@ -27,7 +28,7 @@ const bccInput = ref('')
|
|||
const toInputEl = ref<HTMLInputElement | null>(null)
|
||||
const ccInputEl = ref<HTMLInputElement | null>(null)
|
||||
const bccInputEl = ref<HTMLInputElement | null>(null)
|
||||
const bodyEl = ref<HTMLTextAreaElement | null>(null)
|
||||
const bodyEl = ref<InstanceType<typeof ComposeEditor> | null>(null)
|
||||
|
||||
// ── Quote ─────────────────────────────────────────────────
|
||||
const quoteExpanded = ref(true)
|
||||
|
|
@ -111,6 +112,7 @@ let dragCounter = 0
|
|||
|
||||
// ── Status ────────────────────────────────────────────────
|
||||
const sending = ref(false)
|
||||
const readingClipboard = ref<boolean>(false)
|
||||
const sendError = ref('')
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────
|
||||
|
|
@ -242,6 +244,7 @@ function onDrop(e: DragEvent): void {
|
|||
|
||||
// ── Send ──────────────────────────────────────────────────
|
||||
async function handleSend(): Promise<void> {
|
||||
if (sending.value || readingClipboard.value) return
|
||||
commitInput('to'); commitInput('cc'); commitInput('bcc')
|
||||
await nextTick()
|
||||
|
||||
|
|
@ -251,6 +254,7 @@ async function handleSend(): Promise<void> {
|
|||
sending.value = true
|
||||
sendError.value = ''
|
||||
try {
|
||||
const content = bodyEl.value?.readContent()
|
||||
const sess = toRaw(session.value)
|
||||
const result = await invoke('messages:send', {
|
||||
accountId: sess.accountId,
|
||||
|
|
@ -259,7 +263,9 @@ async function handleSend(): Promise<void> {
|
|||
cc: [...cc.value],
|
||||
bcc: [...bcc.value],
|
||||
subject: subject.value,
|
||||
body: body.value,
|
||||
body: content?.text ?? body.value,
|
||||
contentHtml: content?.html,
|
||||
inlineImages: content?.images,
|
||||
quotedText: quotedText.value || undefined,
|
||||
htmlBody: htmlBody.value || undefined,
|
||||
attachments: attachments.value.map(({ path, filename, size }) => ({ path, filename, size })),
|
||||
|
|
@ -412,10 +418,12 @@ const totalAttachSize = computed(() =>
|
|||
|
||||
<!-- ── Body area ───────────────────────────────────── -->
|
||||
<div class="body-area">
|
||||
<textarea
|
||||
<ComposeEditor
|
||||
ref="bodyEl"
|
||||
class="compose-body"
|
||||
v-model="body"
|
||||
:initial-text="body"
|
||||
@busy="readingClipboard = $event"
|
||||
@error="sendError = $event"
|
||||
:placeholder="isReplyOrForward ? 'Напишите ответ…' : 'Напишите сообщение…'"
|
||||
/>
|
||||
|
||||
|
|
@ -503,7 +511,7 @@ const totalAttachSize = computed(() =>
|
|||
<div class="footer-actions">
|
||||
<span class="shortcut-hint">Ctrl+Enter</span>
|
||||
<button class="btn-cancel" @click="() => window.close()">Отмена</button>
|
||||
<button class="btn-send" :disabled="sending" @click="handleSend">
|
||||
<button class="btn-send" :disabled="sending || readingClipboard" @click="handleSend">
|
||||
<span v-if="sending" class="spinner-sm" />
|
||||
<AppIcon v-else name="send" :size="13" />
|
||||
{{ sending ? 'Отправка…' : 'Отправить' }}
|
||||
|
|
@ -763,7 +771,7 @@ const totalAttachSize = computed(() =>
|
|||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.compose-body::placeholder {
|
||||
.compose-body:empty::before {
|
||||
color: rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
|
|
@ -1326,7 +1334,7 @@ html[data-design='material3'] .compose-body {
|
|||
letter-spacing: var(--md-sys-typescale-body-large-tracking);
|
||||
}
|
||||
|
||||
html[data-design='material3'] .compose-body::placeholder {
|
||||
html[data-design='material3'] .compose-body:empty::before {
|
||||
color: color-mix(in srgb, var(--md-sys-color-on-surface-variant) 50%, transparent);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -53,6 +53,13 @@ export interface ComposeAttachment {
|
|||
size: number
|
||||
}
|
||||
|
||||
export interface ComposeInlineImage {
|
||||
cid: string
|
||||
filename: string
|
||||
contentType: string
|
||||
base64: string
|
||||
}
|
||||
|
||||
export interface ComposeData {
|
||||
to: string[]
|
||||
cc: string[]
|
||||
|
|
@ -61,6 +68,8 @@ export interface ComposeData {
|
|||
body: string // Текст пользователя (без цитаты)
|
||||
quotedText?: string // Plain-text цитата оригинала (> строки с атрибуцией)
|
||||
htmlBody?: string // HTML-блокквота оригинала (для рендера в compose + text/html часть)
|
||||
contentHtml?: string
|
||||
inlineImages?: ComposeInlineImage[]
|
||||
attachments?: ComposeAttachment[]
|
||||
inReplyTo?: string // Message-ID оригинала (для ответа)
|
||||
references?: string // References header
|
||||
|
|
|
|||
Loading…
Reference in a new issue