Merge feature/thread-view: тред-вид писем

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
d.a.kolesov 2026-04-01 14:06:24 +07:00
commit 8f33725a4a
7 changed files with 643 additions and 43 deletions

View file

@ -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<string>
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,
}
}

View file

@ -14,6 +14,7 @@ export type IconName =
| 'attachment'
| 'envelope'
| 'refresh'
| 'threads'
const props = defineProps<{
name: IconName
@ -82,6 +83,12 @@ const paths: Record<IconName, string> = {
<polyline points="23 4 23 10 17 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>

View file

@ -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<Thread[]>(() => buildThreads(messagesStore.filteredMessages))
const expandedThreadIds = ref(new Set<string>())
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<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
@ -175,29 +199,6 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
</div>
</div>
<!-- Панель действий при мультивыборе -->
<div v-if="selectMode && hasSelected" class="bulk-actions">
<span class="bulk-count">
<span class="bulk-count-num">{{ messagesStore.selectedIds.size }}</span>
выбрано
</span>
<div class="bulk-btns">
<button class="bulk-btn" @click="messagesStore.markSelectedAsRead()">
<AppIcon name="envelope" :size="12" />
<span>Прочитать</span>
</button>
<button class="bulk-btn" @click="messagesStore.flagSelected()">
<AppIcon name="flag" :size="12" />
<span>Флажок</span>
</button>
<button class="bulk-btn danger" @click="messagesStore.deleteSelected()">
<AppIcon name="trash" :size="12" />
<span>Удалить</span>
</button>
</div>
<button class="bulk-cancel" @click="exitSelectMode">Отмена</button>
</div>
<!-- Pull-to-refresh индикатор (всегда в DOM, высота = 0 в обычном состоянии) -->
<div
class="pull-indicator-wrap"
@ -239,7 +240,30 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
<span>{{ messagesStore.unreadOnly ? 'Нет непрочитанных писем' : 'В папке нет писем' }}</span>
</div>
<!-- Список писем -->
<!-- Панель действий при мультивыборе -->
<div v-if="selectMode && hasSelected" class="bulk-actions">
<span class="bulk-count">
<span class="bulk-count-num">{{ messagesStore.selectedIds.size }}</span>
выбрано
</span>
<div class="bulk-btns">
<button class="bulk-btn" @click="messagesStore.markSelectedAsRead()">
<AppIcon name="envelope" :size="12" />
<span>Прочитать</span>
</button>
<button class="bulk-btn" @click="messagesStore.flagSelected()">
<AppIcon name="flag" :size="12" />
<span>Флажок</span>
</button>
<button class="bulk-btn danger" @click="messagesStore.deleteSelected()">
<AppIcon name="trash" :size="12" />
<span>Удалить</span>
</button>
</div>
<button class="bulk-cancel" @click="exitSelectMode">Отмена</button>
</div>
<!-- Список тредов -->
<div v-else class="message-list" @scroll="onScroll" @wheel="onWheel">
<!-- Строка "выбрать все" — только в режиме выбора -->
<div v-if="selectMode" class="select-all-row" @click="toggleSelectAll">
@ -255,19 +279,53 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
<span class="select-all-text">Выбрать все</span>
</div>
<MessageListItem
v-for="message in messagesStore.filteredMessages"
:key="message.id"
:message="message"
:selected="messagesStore.selectedMessageId === message.id"
:checked="messagesStore.selectedIds.has(message.id)"
:select-mode="selectMode"
:swipe-left-action="settingsStore.swipeLeftAction"
:swipe-right-action="settingsStore.swipeRightAction"
@click="messagesStore.selectMessage(message.id)"
@toggle-select="messagesStore.toggleSelect(message.id)"
@swipe-action="(action) => handleSwipeAction(action, message.id)"
/>
<template v-for="thread in threads" :key="thread.id">
<!-- Одно письмо — напрямую, без обёртки -->
<MessageListItem
v-if="thread.messages.length === 1"
:message="thread.messages[0]"
:selected="messagesStore.selectedMessageId === thread.messages[0].id"
:checked="messagesStore.selectedIds.has(thread.messages[0].id)"
:select-mode="selectMode"
:swipe-left-action="settingsStore.swipeLeftAction"
:swipe-right-action="settingsStore.swipeRightAction"
@click="messagesStore.selectMessage(thread.messages[0].id)"
@toggle-select="messagesStore.toggleSelect(thread.messages[0].id)"
@swipe-action="(action) => handleSwipeAction(action, thread.messages[0].id)"
/>
<!-- Несколько писем — glass-панель -->
<div
v-else
class="thread-group"
:class="{ 'thread-group--open': expandedThreadIds.has(thread.id) }"
>
<ThreadListItem
:thread="thread"
:expanded="expandedThreadIds.has(thread.id)"
:selected="thread.messages.some(m => messagesStore.selectedMessageId === m.id)"
@click="toggleThread(thread)"
/>
<Transition name="thread-expand">
<div v-if="expandedThreadIds.has(thread.id)" class="thread-children">
<MessageListItem
v-for="(msg, i) in thread.messages"
:key="msg.id"
:message="msg"
:selected="messagesStore.selectedMessageId === msg.id"
:checked="messagesStore.selectedIds.has(msg.id)"
:select-mode="selectMode"
:swipe-left-action="settingsStore.swipeLeftAction"
:swipe-right-action="settingsStore.swipeRightAction"
:class="['thread-child-item', { 'thread-child-last': i === thread.messages.length - 1 }]"
@click="messagesStore.selectMessage(msg.id)"
@toggle-select="messagesStore.toggleSelect(msg.id)"
@swipe-action="(action) => handleSwipeAction(action, msg.id)"
/>
</div>
</Transition>
</div>
</template>
<div v-if="messagesStore.loading" class="loading-more">
<div class="spinner-sm" /> Загрузка...
@ -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);
}
</style>

View file

@ -0,0 +1,296 @@
<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
expanded?: 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-card" :class="{ selected, unread: isUnread, expanded }">
<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>
<svg
class="thread-chevron"
:class="{ open: expanded }"
width="10" height="10" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2.5"
stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9"/>
</svg>
</div>
<!-- Строка 3: сниппет последнего письма -->
<div v-if="snippet" class="thread-snippet truncate">
{{ snippet }}
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* Внешняя карточка — glass border, margin, radius */
.thread-card {
position: relative;
margin: 2px 5px;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.025);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05);
overflow: hidden;
transition:
border-color var(--transition-fast),
box-shadow var(--transition-fast);
}
.thread-card:hover {
border-color: rgba(255, 255, 255, 0.10);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 3px 10px rgba(0, 0, 0, 0.25);
}
.thread-card.unread {
background:
linear-gradient(180deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.015) 100%),
#0d0d17;
}
.thread-card.selected {
border-color: rgba(255, 255, 255, 0.18);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
z-index: 1;
}
.thread-item {
display: flex;
align-items: flex-start;
gap: 2px;
padding: 10px 10px 10px 4px;
cursor: pointer;
position: relative;
/* Выбранное: glass fill */
transition: background var(--transition-fast);
}
.thread-item.selected {
background: linear-gradient(
145deg,
rgba(255, 255, 255, 0.10) 0%,
var(--bg-selected) 100%
);
}
.thread-item.selected::before {
content: '';
position: absolute;
left: 0;
top: 20%;
bottom: 20%;
width: 2.5px;
border-radius: 2px;
background: var(--accent);
}
.thread-item:not(.selected):hover {
background:
linear-gradient(180deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.035) 100%),
#0c0c14;
}
/* Точка непрочитанного */
.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;
}
.thread-chevron {
flex-shrink: 0;
color: var(--text-muted);
transition: transform var(--transition-fast), color var(--transition-fast);
}
.thread-chevron.open {
transform: rotate(180deg);
color: var(--accent);
}
/* Раскрытый тред */
.thread-card.expanded {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
border-color: color-mix(in srgb, var(--accent) 30%, rgba(255,255,255,0.08));
border-bottom-color: color-mix(in srgb, var(--accent) 15%, transparent);
background:
linear-gradient(180deg, color-mix(in srgb, var(--accent) 6%, transparent) 0%, transparent 100%),
rgba(255, 255, 255, 0.04);
box-shadow:
inset 0 1px 0 color-mix(in srgb, var(--accent) 20%, rgba(255,255,255,0.08)),
0 2px 12px rgba(0, 0, 0, 0.2);
}
.thread-card.expanded .thread-item {
background: transparent;
}
</style>

View file

@ -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 {

View 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()
)
}

View file

@ -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 {