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..ccc3f68 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,19 @@ const allVisibleSelected = computed(() => messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id)) ) +// ── Thread mode ─────────────────────────────────────────── +const threads = computed(() => + settingsStore.threadMode ? buildThreads(messagesStore.filteredMessages) : [] +) + +const selectedThreadId = ref(null) + +function selectThread(thread: Thread): void { + selectedThreadId.value = thread.id + // Открываем последнее (новое) письмо треда + messagesStore.selectMessage(thread.latest.id) +} + // ── Refresh ─────────────────────────────────────────────── async function refresh(): Promise { if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return @@ -151,6 +166,14 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis {{ activeUnread }}
+
- +
- -
- - - - - - - Выбрать все -
- + + + + +
Загрузка... diff --git a/src/renderer/src/components/messages/ThreadListItem.vue b/src/renderer/src/components/messages/ThreadListItem.vue new file mode 100644 index 0000000..5e5bf78 --- /dev/null +++ b/src/renderer/src/components/messages/ThreadListItem.vue @@ -0,0 +1,216 @@ + + + + + diff --git a/src/renderer/src/stores/settings.store.ts b/src/renderer/src/stores/settings.store.ts index 6d9a7d2..1c7a359 100644 --- a/src/renderer/src/stores/settings.store.ts +++ b/src/renderer/src/stores/settings.store.ts @@ -85,6 +85,7 @@ function load(): { accentColor?: string autoCheckInterval?: number uiScale?: number + threadMode?: boolean } { try { return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') @@ -101,6 +102,7 @@ export const useSettingsStore = defineStore('settings', () => { const accentColor = ref(saved.accentColor ?? '#a8e600') const autoCheckInterval = ref(saved.autoCheckInterval ?? 5) const uiScale = ref(saved.uiScale ?? 1.0) + const threadMode = ref(saved.threadMode ?? false) // Apply on init applyAccentColor(accentColor.value) @@ -116,7 +118,7 @@ export const useSettingsStore = defineStore('settings', () => { persist() }) - watch([swipeLeftAction, swipeRightAction, autoCheckInterval], persist) + watch([swipeLeftAction, swipeRightAction, autoCheckInterval, threadMode], persist) function persist(): void { localStorage.setItem(STORAGE_KEY, JSON.stringify({ @@ -125,8 +127,9 @@ export const useSettingsStore = defineStore('settings', () => { accentColor: accentColor.value, autoCheckInterval: autoCheckInterval.value, uiScale: uiScale.value, + threadMode: threadMode.value, })) } - return { swipeLeftAction, swipeRightAction, accentColor, autoCheckInterval, uiScale } + return { swipeLeftAction, swipeRightAction, accentColor, autoCheckInterval, uiScale, threadMode } }) 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 {