diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index 9eb7000..1b029a7 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -302,6 +302,8 @@ export class ImapProvider implements IEmailProvider { to?: Array<{ name?: string; address?: string }> cc?: Array<{ name?: string; address?: string }> date?: Date + messageId?: string + inReplyTo?: string } flags: Set bodyStructure?: BodyPart @@ -327,7 +329,9 @@ export class ImapProvider implements IEmailProvider { deleted: flags.has('\\Deleted') }, hasAttachments: this.hasAttachments(m.bodyStructure), - snippet: '' + snippet: '', + messageId: m.envelope?.messageId ?? undefined, + inReplyTo: m.envelope?.inReplyTo ?? undefined, } } diff --git a/src/renderer/src/components/AppIcon.vue b/src/renderer/src/components/AppIcon.vue index 69b29fe..18cf0cb 100644 --- a/src/renderer/src/components/AppIcon.vue +++ b/src/renderer/src/components/AppIcon.vue @@ -14,6 +14,7 @@ export type IconName = | 'attachment' | 'envelope' | 'refresh' + | 'threads' const props = defineProps<{ name: IconName @@ -82,6 +83,12 @@ const paths: Record = { `, + threads: ` + + + + + `, } diff --git a/src/renderer/src/components/messages/MessageList.vue b/src/renderer/src/components/messages/MessageList.vue index 740e6bc..e9c8cf9 100644 --- a/src/renderer/src/components/messages/MessageList.vue +++ b/src/renderer/src/components/messages/MessageList.vue @@ -5,7 +5,9 @@ import { useFoldersStore } from '../../stores/folders.store' import { useAccountsStore } from '../../stores/accounts.store' import { useSettingsStore, type SwipeAction } from '../../stores/settings.store' import MessageListItem from './MessageListItem.vue' +import ThreadListItem from './ThreadListItem.vue' import AppIcon from '../AppIcon.vue' +import { buildThreads, type Thread } from '../../utils/threading' const messagesStore = useMessagesStore() const foldersStore = useFoldersStore() @@ -25,6 +27,28 @@ const allVisibleSelected = computed(() => messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id)) ) +// ── Threads ─────────────────────────────────────────────── +const threads = computed(() => buildThreads(messagesStore.filteredMessages)) + +const expandedThreadIds = ref(new Set()) + +function toggleThread(thread: Thread): void { + if (thread.messages.length === 1) { + // Один элемент — открываем напрямую + messagesStore.selectMessage(thread.messages[0].id) + return + } + if (expandedThreadIds.value.has(thread.id)) { + expandedThreadIds.value.delete(thread.id) + } else { + expandedThreadIds.value.add(thread.id) + // Открываем последнее письмо треда + messagesStore.selectMessage(thread.latest.id) + } + // trigger reactivity + expandedThreadIds.value = new Set(expandedThreadIds.value) +} + // ── Refresh ─────────────────────────────────────────────── async function refresh(): Promise { if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return @@ -175,29 +199,6 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis - -
- - {{ messagesStore.selectedIds.size }} - выбрано - -
- - - -
- -
-
{{ messagesStore.unreadOnly ? 'Нет непрочитанных писем' : 'В папке нет писем' }}
- + +
+ + {{ messagesStore.selectedIds.size }} + выбрано + +
+ + + +
+ +
+ +
@@ -255,19 +279,53 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis Выбрать все
- +
Загрузка... @@ -695,4 +753,98 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis @keyframes spin { to { transform: rotate(360deg); } } + +/* ── Группа треда ───────────────────────────────────────── */ +.thread-group { + /* collapsed: без стилей — ThreadListItem рендерит собственную карточку */ +} + +/* Открытый тред — единая glass-панель */ +.thread-group--open { + position: relative; + margin: 2px 5px; + border-radius: 10px; + overflow: hidden; + background: linear-gradient( + 135deg, + color-mix(in srgb, var(--accent) 14%, transparent) 0%, + color-mix(in srgb, var(--accent) 5%, transparent) 50%, + transparent 100% + ); + backdrop-filter: blur(40px) saturate(1.8); + -webkit-backdrop-filter: blur(40px) saturate(1.8); + border: 1px solid rgba(255, 255, 255, 0.13); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.18), + 0 4px 24px rgba(0, 0, 0, 0.30); + z-index: 1; +} + +/* Призматическая верхняя грань */ +.thread-group--open::before { + content: ''; + position: absolute; + left: 0; + top: 0; + right: 0; + height: 1px; + background: linear-gradient( + 90deg, + transparent 0%, + rgba(255, 120, 120, 0.55) 12%, + rgba(255, 200, 80, 0.55) 28%, + rgba(200, 255, 100, 0.55) 45%, + rgba( 80, 200, 255, 0.55) 62%, + rgba(160, 100, 255, 0.55) 78%, + rgba(255, 120, 200, 0.55) 92%, + transparent 100% + ); + pointer-events: none; + z-index: 3; +} + +/* Заголовок треда внутри открытой панели: убираем собственную карточку */ +.thread-group--open :deep(.thread-card), +.thread-group--open :deep(.thread-card.expanded) { + margin: 0; + border: none; + border-radius: 0; + background: transparent; + box-shadow: none; + border-bottom: 1px solid rgba(255, 255, 255, 0.07); +} + +/* Контейнер дочерних писем */ +.thread-children { + overflow: hidden; +} + +/* Дочерние письма: убираем собственные карточки, они — ряды внутри панели */ +:deep(.thread-child-item) { + margin: 0 !important; + border-radius: 0 !important; + border: none !important; + box-shadow: none !important; +} + +/* Разделитель между соседними дочерними письмами */ +.thread-children :deep(.thread-child-item:not(:first-child) .message-item) { + border-top: 1px solid rgba(255, 255, 255, 0.04); +} + +/* ── Анимация раскрытия ─────────────────────────────────── */ +.thread-expand-enter-active { + transition: opacity 180ms ease, transform 220ms cubic-bezier(0.34, 1.1, 0.64, 1); +} +.thread-expand-leave-active { + transition: opacity 140ms ease, transform 160ms ease; +} +.thread-expand-enter-from { + opacity: 0; + transform: translateY(-6px); +} +.thread-expand-leave-to { + opacity: 0; + transform: translateY(-4px); +} diff --git a/src/renderer/src/components/messages/ThreadListItem.vue b/src/renderer/src/components/messages/ThreadListItem.vue new file mode 100644 index 0000000..8a055f0 --- /dev/null +++ b/src/renderer/src/components/messages/ThreadListItem.vue @@ -0,0 +1,296 @@ + + + + + diff --git a/src/renderer/src/utils/date.ts b/src/renderer/src/utils/date.ts index 45c0151..f93c8df 100644 --- a/src/renderer/src/utils/date.ts +++ b/src/renderer/src/utils/date.ts @@ -1,21 +1,26 @@ -import { formatDistanceToNow, format, isToday, isYesterday, isThisYear } from 'date-fns' +import { format, isToday, isYesterday, startOfWeek } from 'date-fns' +import { ru } from 'date-fns/locale' export function formatMessageDate(dateStr: string): string { const date = new Date(dateStr) + const now = new Date() if (isToday(date)) { return format(date, 'HH:mm') } if (isYesterday(date)) { - return 'Yesterday' + return `Вчера ${format(date, 'HH:mm')}` } - if (isThisYear(date)) { - return format(date, 'MMM d') + const weekStart = startOfWeek(now, { weekStartsOn: 1 }) + if (date >= weekStart) { + // Первая буква заглавная: "Понедельник 14:30" + const str = format(date, 'EEEE HH:mm', { locale: ru }) + return str.charAt(0).toUpperCase() + str.slice(1) } - return format(date, 'MMM d, yyyy') + return format(date, 'yyyy-MM-dd HH:mm') } export function formatFullDate(dateStr: string): string { diff --git a/src/renderer/src/utils/threading.ts b/src/renderer/src/utils/threading.ts new file mode 100644 index 0000000..188248d --- /dev/null +++ b/src/renderer/src/utils/threading.ts @@ -0,0 +1,134 @@ +import type { MessageEnvelope, Address } from '@shared/types/message' + +export interface Thread { + id: string + subject: string + messages: MessageEnvelope[] // отсортированы по дате, от старого к новому + latest: MessageEnvelope + unreadCount: number + participants: Address[] // уникальные, в порядке появления + hasAttachments: boolean +} + +/** Нормализует тему: убирает Re:/Fwd:/АВ: и т.п. */ +function normalizeSubject(subject: string): string { + return subject + .replace(/^\s*(Re|Fwd?|AW|Ответ|Отв|Пер|ΑΠ|SV|Vs?|VS)\s*:\s*/i, '') + .trim() + .toLowerCase() +} + +function uniqueParticipants(messages: MessageEnvelope[]): Address[] { + const seen = new Set() + const result: Address[] = [] + for (const m of messages) { + const key = m.from.email.toLowerCase() + if (!seen.has(key)) { + seen.add(key) + result.push(m.from) + } + } + return result +} + +/** + * Группирует плоский список писем в треды. + * + * Алгоритм (двухпроходный): + * 1. Пробуем связать по inReplyTo → messageId (RFC 2822 threading) + * 2. Оставшиеся письма группируем по нормализованной теме + */ +export function buildThreads(messages: MessageEnvelope[]): Thread[] { + if (messages.length === 0) return [] + + // --- Pass 1: threading по заголовкам --- + const byMsgId = new Map() + for (const m of messages) { + if (m.messageId) byMsgId.set(m.messageId, m) + } + + // thread-id каждого письма: если письмо — ответ, ищем корень цепочки + const threadIdOf = new Map() + + function getRootId(m: MessageEnvelope): string { + if (!m.inReplyTo) return m.messageId ?? m.id + const parent = byMsgId.get(m.inReplyTo) + if (!parent) return m.messageId ?? m.id + // рекурсивный подъём к корню (защита от циклов через visited) + const visited = new Set() + let cur: MessageEnvelope = parent + while (cur.inReplyTo && !visited.has(cur.id)) { + visited.add(cur.id) + const p = byMsgId.get(cur.inReplyTo) + if (!p) break + cur = p + } + return cur.messageId ?? cur.id + } + + // Присваиваем threadId через inReplyTo + const headerThreads = new Map() + const unassigned: MessageEnvelope[] = [] + + for (const m of messages) { + if (m.inReplyTo && byMsgId.has(m.inReplyTo)) { + const rootId = getRootId(m) + threadIdOf.set(m.id, rootId) + const bucket = headerThreads.get(rootId) ?? [] + bucket.push(m) + headerThreads.set(rootId, bucket) + } else { + unassigned.push(m) + } + } + + // Добавляем корневые письма в свои треды + for (const m of messages) { + const rootId = m.messageId ?? m.id + if (headerThreads.has(rootId)) { + // корень треда ещё не добавлен как участник + if (!headerThreads.get(rootId)!.some((x) => x.id === m.id)) { + headerThreads.get(rootId)!.push(m) + // убираем из unassigned + const idx = unassigned.indexOf(m) + if (idx !== -1) unassigned.splice(idx, 1) + } + } + } + + // --- Pass 2: subject-based grouping для оставшихся --- + const subjectGroups = new Map() + for (const m of unassigned) { + const key = normalizeSubject(m.subject) + const bucket = subjectGroups.get(key) ?? [] + bucket.push(m) + subjectGroups.set(key, bucket) + } + + // --- Собираем финальные треды --- + const allBuckets: MessageEnvelope[][] = [ + ...headerThreads.values(), + ...subjectGroups.values(), + ] + + const threads: Thread[] = allBuckets.map((msgs) => { + const sorted = [...msgs].sort( + (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime() + ) + const latest = sorted[sorted.length - 1] + return { + id: sorted[0].messageId ?? sorted[0].id, + subject: sorted[0].subject, + messages: sorted, + latest, + unreadCount: sorted.filter((m) => !m.flags.seen).length, + participants: uniqueParticipants(sorted), + hasAttachments: sorted.some((m) => m.hasAttachments), + } + }) + + // Сортируем треды по дате последнего письма (новые — сверху) + return threads.sort( + (a, b) => new Date(b.latest.date).getTime() - new Date(a.latest.date).getTime() + ) +} diff --git a/src/shared/types/message.ts b/src/shared/types/message.ts index 6c15cf5..2825078 100644 --- a/src/shared/types/message.ts +++ b/src/shared/types/message.ts @@ -21,6 +21,8 @@ export interface MessageEnvelope { flags: MessageFlags hasAttachments: boolean snippet: string + messageId?: string // Message-ID header + inReplyTo?: string // In-Reply-To header } export interface InlineImage {