feature/thread-view: группировка писем в треды
- MessageEnvelope: добавлены поля messageId, inReplyTo - imap.provider: извлекаем messageId/inReplyTo из envelope (есть в IMAP FETCH) - threading.ts: двухпроходный алгоритм (inReplyTo-цепочки → subject fallback) - ThreadListItem.vue: карточка треда с участниками, счётчиком писем, бейджем unread - AppIcon: иконка threads (speech bubble с точками) - settings.store: threadMode (boolean, persisted) - MessageList: кнопка-переключатель в хедере, условный рендер тредов/писем Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
9f1cde5b17
commit
28a42c8f79
7 changed files with 433 additions and 30 deletions
|
|
@ -302,6 +302,8 @@ export class ImapProvider implements IEmailProvider {
|
||||||
to?: Array<{ name?: string; address?: string }>
|
to?: Array<{ name?: string; address?: string }>
|
||||||
cc?: Array<{ name?: string; address?: string }>
|
cc?: Array<{ name?: string; address?: string }>
|
||||||
date?: Date
|
date?: Date
|
||||||
|
messageId?: string
|
||||||
|
inReplyTo?: string
|
||||||
}
|
}
|
||||||
flags: Set<string>
|
flags: Set<string>
|
||||||
bodyStructure?: BodyPart
|
bodyStructure?: BodyPart
|
||||||
|
|
@ -327,7 +329,9 @@ export class ImapProvider implements IEmailProvider {
|
||||||
deleted: flags.has('\\Deleted')
|
deleted: flags.has('\\Deleted')
|
||||||
},
|
},
|
||||||
hasAttachments: this.hasAttachments(m.bodyStructure),
|
hasAttachments: this.hasAttachments(m.bodyStructure),
|
||||||
snippet: ''
|
snippet: '',
|
||||||
|
messageId: m.envelope?.messageId ?? undefined,
|
||||||
|
inReplyTo: m.envelope?.inReplyTo ?? undefined,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ export type IconName =
|
||||||
| 'attachment'
|
| 'attachment'
|
||||||
| 'envelope'
|
| 'envelope'
|
||||||
| 'refresh'
|
| 'refresh'
|
||||||
|
| 'threads'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
name: IconName
|
name: IconName
|
||||||
|
|
@ -82,6 +83,12 @@ const paths: Record<IconName, string> = {
|
||||||
<polyline points="23 4 23 10 17 10"/>
|
<polyline points="23 4 23 10 17 10"/>
|
||||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||||
`,
|
`,
|
||||||
|
threads: `
|
||||||
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
||||||
|
<line x1="9" y1="10" x2="9.01" y2="10" stroke-width="2.5"/>
|
||||||
|
<line x1="13" y1="10" x2="13.01" y2="10" stroke-width="2.5"/>
|
||||||
|
<line x1="17" y1="10" x2="17.01" y2="10" stroke-width="2.5"/>
|
||||||
|
`,
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,9 @@ import { useFoldersStore } from '../../stores/folders.store'
|
||||||
import { useAccountsStore } from '../../stores/accounts.store'
|
import { useAccountsStore } from '../../stores/accounts.store'
|
||||||
import { useSettingsStore, type SwipeAction } from '../../stores/settings.store'
|
import { useSettingsStore, type SwipeAction } from '../../stores/settings.store'
|
||||||
import MessageListItem from './MessageListItem.vue'
|
import MessageListItem from './MessageListItem.vue'
|
||||||
|
import ThreadListItem from './ThreadListItem.vue'
|
||||||
import AppIcon from '../AppIcon.vue'
|
import AppIcon from '../AppIcon.vue'
|
||||||
|
import { buildThreads, type Thread } from '../../utils/threading'
|
||||||
|
|
||||||
const messagesStore = useMessagesStore()
|
const messagesStore = useMessagesStore()
|
||||||
const foldersStore = useFoldersStore()
|
const foldersStore = useFoldersStore()
|
||||||
|
|
@ -25,6 +27,19 @@ const allVisibleSelected = computed(() =>
|
||||||
messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id))
|
messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ── Thread mode ───────────────────────────────────────────
|
||||||
|
const threads = computed<Thread[]>(() =>
|
||||||
|
settingsStore.threadMode ? buildThreads(messagesStore.filteredMessages) : []
|
||||||
|
)
|
||||||
|
|
||||||
|
const selectedThreadId = ref<string | null>(null)
|
||||||
|
|
||||||
|
function selectThread(thread: Thread): void {
|
||||||
|
selectedThreadId.value = thread.id
|
||||||
|
// Открываем последнее (новое) письмо треда
|
||||||
|
messagesStore.selectMessage(thread.latest.id)
|
||||||
|
}
|
||||||
|
|
||||||
// ── Refresh ───────────────────────────────────────────────
|
// ── Refresh ───────────────────────────────────────────────
|
||||||
async function refresh(): Promise<void> {
|
async function refresh(): Promise<void> {
|
||||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||||
|
|
@ -151,6 +166,14 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
{{ activeUnread }}
|
{{ activeUnread }}
|
||||||
</button>
|
</button>
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<button
|
||||||
|
class="icon-btn"
|
||||||
|
:class="{ active: settingsStore.threadMode }"
|
||||||
|
title="Режим тредов"
|
||||||
|
@click="settingsStore.threadMode = !settingsStore.threadMode"
|
||||||
|
>
|
||||||
|
<AppIcon name="threads" :size="14" />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
class="icon-btn select-mode-btn"
|
class="icon-btn select-mode-btn"
|
||||||
:class="{ active: selectMode }"
|
:class="{ active: selectMode }"
|
||||||
|
|
@ -239,9 +262,22 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
<span>{{ messagesStore.unreadOnly ? 'Нет непрочитанных писем' : 'В папке нет писем' }}</span>
|
<span>{{ messagesStore.unreadOnly ? 'Нет непрочитанных писем' : 'В папке нет писем' }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Список писем -->
|
<!-- Список писем / тредов -->
|
||||||
<div v-else class="message-list" @scroll="onScroll" @wheel="onWheel">
|
<div v-else class="message-list" @scroll="onScroll" @wheel="onWheel">
|
||||||
<!-- Строка "выбрать все" — только в режиме выбора -->
|
|
||||||
|
<!-- ── Режим тредов ── -->
|
||||||
|
<template v-if="settingsStore.threadMode">
|
||||||
|
<ThreadListItem
|
||||||
|
v-for="thread in threads"
|
||||||
|
:key="thread.id"
|
||||||
|
:thread="thread"
|
||||||
|
:selected="selectedThreadId === thread.id"
|
||||||
|
@click="selectThread(thread)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- ── Обычный режим ── -->
|
||||||
|
<template v-else>
|
||||||
<div v-if="selectMode" class="select-all-row" @click="toggleSelectAll">
|
<div v-if="selectMode" class="select-all-row" @click="toggleSelectAll">
|
||||||
<span
|
<span
|
||||||
class="select-all-circle"
|
class="select-all-circle"
|
||||||
|
|
@ -268,6 +304,7 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
@toggle-select="messagesStore.toggleSelect(message.id)"
|
@toggle-select="messagesStore.toggleSelect(message.id)"
|
||||||
@swipe-action="(action) => handleSwipeAction(action, message.id)"
|
@swipe-action="(action) => handleSwipeAction(action, message.id)"
|
||||||
/>
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
<div v-if="messagesStore.loading" class="loading-more">
|
<div v-if="messagesStore.loading" class="loading-more">
|
||||||
<div class="spinner-sm" /> Загрузка...
|
<div class="spinner-sm" /> Загрузка...
|
||||||
|
|
|
||||||
216
src/renderer/src/components/messages/ThreadListItem.vue
Normal file
216
src/renderer/src/components/messages/ThreadListItem.vue
Normal file
|
|
@ -0,0 +1,216 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import type { Thread } from '../../utils/threading'
|
||||||
|
import { formatMessageDate } from '../../utils/date'
|
||||||
|
import AppIcon from '../AppIcon.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
thread: Thread
|
||||||
|
selected: boolean
|
||||||
|
}>()
|
||||||
|
|
||||||
|
defineEmits<{ click: [] }>()
|
||||||
|
|
||||||
|
const isUnread = computed(() => props.thread.unreadCount > 0)
|
||||||
|
const dateDisplay = computed(() => formatMessageDate(props.thread.latest.date))
|
||||||
|
|
||||||
|
const participantNames = computed(() => {
|
||||||
|
return props.thread.participants
|
||||||
|
.slice(0, 3)
|
||||||
|
.map((p) => p.name || p.email.split('@')[0])
|
||||||
|
.join(', ')
|
||||||
|
})
|
||||||
|
|
||||||
|
const normalizedSubject = computed(() => {
|
||||||
|
// Убираем Re:/Fwd: для отображения
|
||||||
|
return props.thread.subject
|
||||||
|
.replace(/^\s*(Re|Fwd?|AW|Ответ|Отв|Пер)\s*:\s*/i, '')
|
||||||
|
.trim() || '(без темы)'
|
||||||
|
})
|
||||||
|
|
||||||
|
const snippet = computed(() => props.thread.latest.snippet || '')
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="thread-item"
|
||||||
|
:class="{ selected, unread: isUnread }"
|
||||||
|
@click="$emit('click')"
|
||||||
|
>
|
||||||
|
<!-- Индикатор непрочитанных -->
|
||||||
|
<div class="unread-dot-wrap">
|
||||||
|
<span v-if="isUnread" class="unread-dot" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Основной контент -->
|
||||||
|
<div class="thread-content">
|
||||||
|
<!-- Строка 1: участники + дата -->
|
||||||
|
<div class="thread-row1">
|
||||||
|
<span class="thread-participants" :class="{ bold: isUnread }">
|
||||||
|
{{ participantNames }}
|
||||||
|
</span>
|
||||||
|
<div class="thread-meta">
|
||||||
|
<AppIcon v-if="thread.hasAttachments" name="attachment" :size="11" class="attach-icon" />
|
||||||
|
<span class="thread-date">{{ dateDisplay }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Строка 2: тема + счётчик -->
|
||||||
|
<div class="thread-row2">
|
||||||
|
<span class="thread-subject truncate" :class="{ bold: isUnread }">
|
||||||
|
{{ normalizedSubject }}
|
||||||
|
</span>
|
||||||
|
<span v-if="thread.messages.length > 1" class="thread-count">
|
||||||
|
{{ thread.messages.length }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Строка 3: сниппет последнего письма -->
|
||||||
|
<div v-if="snippet" class="thread-snippet truncate">
|
||||||
|
{{ snippet }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.thread-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 2px;
|
||||||
|
padding: 10px 10px 10px 4px;
|
||||||
|
margin: 1px 4px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background var(--transition-fast);
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-item:hover {
|
||||||
|
background: var(--glass-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-item.selected {
|
||||||
|
background: var(--bg-selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-item.selected::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 20%;
|
||||||
|
bottom: 20%;
|
||||||
|
width: 2.5px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Точка непрочитанного */
|
||||||
|
.unread-dot-wrap {
|
||||||
|
width: 20px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unread-dot {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent);
|
||||||
|
box-shadow: 0 0 6px color-mix(in srgb, var(--accent) 50%, transparent);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Контент */
|
||||||
|
.thread-content {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-row1,
|
||||||
|
.thread-row2 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-participants {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-participants.bold {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attach-icon {
|
||||||
|
color: var(--text-muted);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-date {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-item.unread .thread-date {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-subject {
|
||||||
|
flex: 1;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-subject.bold {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Бейдж с количеством писем */
|
||||||
|
.thread-count {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
background: rgba(255, 255, 255, 0.07);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.10);
|
||||||
|
border-radius: var(--radius-full);
|
||||||
|
padding: 0 5px;
|
||||||
|
line-height: 16px;
|
||||||
|
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-item.unread .thread-count {
|
||||||
|
color: var(--accent);
|
||||||
|
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||||
|
border-color: color-mix(in srgb, var(--accent) 25%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.thread-snippet {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -85,6 +85,7 @@ function load(): {
|
||||||
accentColor?: string
|
accentColor?: string
|
||||||
autoCheckInterval?: number
|
autoCheckInterval?: number
|
||||||
uiScale?: number
|
uiScale?: number
|
||||||
|
threadMode?: boolean
|
||||||
} {
|
} {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}')
|
return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}')
|
||||||
|
|
@ -101,6 +102,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||||
const accentColor = ref<string>(saved.accentColor ?? '#a8e600')
|
const accentColor = ref<string>(saved.accentColor ?? '#a8e600')
|
||||||
const autoCheckInterval = ref<number>(saved.autoCheckInterval ?? 5)
|
const autoCheckInterval = ref<number>(saved.autoCheckInterval ?? 5)
|
||||||
const uiScale = ref<number>(saved.uiScale ?? 1.0)
|
const uiScale = ref<number>(saved.uiScale ?? 1.0)
|
||||||
|
const threadMode = ref<boolean>(saved.threadMode ?? false)
|
||||||
|
|
||||||
// Apply on init
|
// Apply on init
|
||||||
applyAccentColor(accentColor.value)
|
applyAccentColor(accentColor.value)
|
||||||
|
|
@ -116,7 +118,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||||
persist()
|
persist()
|
||||||
})
|
})
|
||||||
|
|
||||||
watch([swipeLeftAction, swipeRightAction, autoCheckInterval], persist)
|
watch([swipeLeftAction, swipeRightAction, autoCheckInterval, threadMode], persist)
|
||||||
|
|
||||||
function persist(): void {
|
function persist(): void {
|
||||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
||||||
|
|
@ -125,8 +127,9 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||||
accentColor: accentColor.value,
|
accentColor: accentColor.value,
|
||||||
autoCheckInterval: autoCheckInterval.value,
|
autoCheckInterval: autoCheckInterval.value,
|
||||||
uiScale: uiScale.value,
|
uiScale: uiScale.value,
|
||||||
|
threadMode: threadMode.value,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
return { swipeLeftAction, swipeRightAction, accentColor, autoCheckInterval, uiScale }
|
return { swipeLeftAction, swipeRightAction, accentColor, autoCheckInterval, uiScale, threadMode }
|
||||||
})
|
})
|
||||||
|
|
|
||||||
134
src/renderer/src/utils/threading.ts
Normal file
134
src/renderer/src/utils/threading.ts
Normal file
|
|
@ -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<string>()
|
||||||
|
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<string, MessageEnvelope>()
|
||||||
|
for (const m of messages) {
|
||||||
|
if (m.messageId) byMsgId.set(m.messageId, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
// thread-id каждого письма: если письмо — ответ, ищем корень цепочки
|
||||||
|
const threadIdOf = new Map<string, string>()
|
||||||
|
|
||||||
|
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<string>()
|
||||||
|
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<string, MessageEnvelope[]>()
|
||||||
|
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<string, MessageEnvelope[]>()
|
||||||
|
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()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -21,6 +21,8 @@ export interface MessageEnvelope {
|
||||||
flags: MessageFlags
|
flags: MessageFlags
|
||||||
hasAttachments: boolean
|
hasAttachments: boolean
|
||||||
snippet: string
|
snippet: string
|
||||||
|
messageId?: string // Message-ID header
|
||||||
|
inReplyTo?: string // In-Reply-To header
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface InlineImage {
|
export interface InlineImage {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue