Merge feature/unread-badges: бейджи непрочитанных в сайдбаре и заголовке

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
vodyanoysh 2026-03-31 23:42:48 +07:00
commit e779c23abd
8 changed files with 191 additions and 23 deletions

View file

@ -2,8 +2,8 @@ import { registerHandler } from './registry'
import type { AccountManager } from '../services/account-manager' import type { AccountManager } from '../services/account-manager'
export function registerMessageHandlers(manager: AccountManager): void { export function registerMessageHandlers(manager: AccountManager): void {
registerHandler('messages:list', async ({ accountId, folderId, offset, limit }) => { registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
return manager.listMessages(accountId, folderId, offset, limit) return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
}) })
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => { registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {

View file

@ -69,20 +69,43 @@ export class ImapProvider implements IEmailProvider {
// listTree() returns { root: true, folders: ImapMailbox[] } // listTree() returns { root: true, folders: ImapMailbox[] }
const tree = await this.client.listTree() as { folders?: ImapMailbox[] } const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const folders = this.convertMailboxArray(tree.folders ?? []) const folders = this.convertMailboxArray(tree.folders ?? [])
await this.populateUnreadCounts(folders)
return { folders } return { folders }
} }
private async populateUnreadCounts(folders: Folder[]): Promise<void> {
for (const folder of folders) {
try {
const status = await this.client.status(folder.id, { unseen: true, messages: true }) as
{ unseen?: number; messages?: number } | null
if (status) {
folder.unreadCount = status.unseen ?? 0
folder.totalCount = status.messages ?? 0
}
} catch {
// Некоторые папки (виртуальные, [Gmail]) могут не поддерживать STATUS
}
if (folder.children.length > 0) {
await this.populateUnreadCounts(folder.children)
}
}
}
async listMessages(options: MessageListOptions): Promise<MessageListResult> { async listMessages(options: MessageListOptions): Promise<MessageListResult> {
const lock = await this.client.getMailboxLock(options.folderId) const lock = await this.client.getMailboxLock(options.folderId)
try { try {
if (options.unseenOnly) {
return await this.listUnseenMessages(options)
}
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0 const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
if (total === 0) return { messages: [], total: 0 } if (total === 0) return { messages: [], total: 0, unseen: 0 }
// IMAP sequence numbers are 1-based, newest = highest number // IMAP sequence numbers are 1-based, newest = highest number
const end = Math.max(1, total - options.offset) const end = Math.max(1, total - options.offset)
const start = Math.max(1, end - options.limit + 1) const start = Math.max(1, end - options.limit + 1)
if (start > total) return { messages: [], total } if (start > total) return { messages: [], total, unseen: 0 }
const messages: MessageEnvelope[] = [] const messages: MessageEnvelope[] = []
@ -98,16 +121,43 @@ export class ImapProvider implements IEmailProvider {
// Newest first // Newest first
messages.reverse() messages.reverse()
return { messages, total } return { messages, total, unseen: 0 }
} finally { } finally {
lock.release() lock.release()
} }
} }
private async listUnseenMessages(options: MessageListOptions): Promise<MessageListResult> {
// Mailbox lock is already held by listMessages caller
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (!uids || uids.length === 0) return { messages: [], total: 0, unseen: 0 }
const total = uids.length
// Sort descending — higher UID = newer message
const sorted = [...uids].sort((a, b) => b - a)
const page = sorted.slice(options.offset, options.offset + options.limit)
if (page.length === 0) return { messages: [], total, unseen: total }
const uidSet = page.join(',')
const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(uidSet, {
uid: true,
envelope: true,
flags: true,
bodyStructure: true
}, { uid: true })) {
messages.push(this.convertMessage(msg, options.folderId))
}
// Fetch returns ascending order → reverse to newest first
messages.sort((a, b) => Number(b.id) - Number(a.id))
return { messages, total, unseen: total }
}
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> { async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
const lock = await this.client.getMailboxLock(folderId) const lock = await this.client.getMailboxLock(folderId)
try { try {
// Download full RFC822 source and parse with mailparser // imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
const download = await this.client.download(messageId, undefined, { uid: true }) const download = await this.client.download(messageId, undefined, { uid: true })
if (!download) { if (!download) {
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] } return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }

View file

@ -125,10 +125,11 @@ export class AccountManager {
accountId: string, accountId: string,
folderId: string, folderId: string,
offset: number, offset: number,
limit: number limit: number,
unseenOnly = false
): Promise<MessageListResult> { ): Promise<MessageListResult> {
const provider = this.getProvider(accountId) const provider = this.getProvider(accountId)
return provider.listMessages({ folderId, offset, limit }) return provider.listMessages({ folderId, offset, limit, unseenOnly })
} }
async fetchMessageBody( async fetchMessageBody(

View file

@ -16,6 +16,10 @@ const selectMode = ref(false)
const folderName = computed(() => foldersStore.activeFolder?.name ?? '') const folderName = computed(() => foldersStore.activeFolder?.name ?? '')
const hasSelected = computed(() => messagesStore.selectedIds.size > 0) const hasSelected = computed(() => messagesStore.selectedIds.size > 0)
const activeUnread = computed(() => {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return 0
return foldersStore.getFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId)
})
const allVisibleSelected = computed(() => const allVisibleSelected = computed(() =>
messagesStore.filteredMessages.length > 0 && messagesStore.filteredMessages.length > 0 &&
messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id)) messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id))
@ -24,7 +28,9 @@ const allVisibleSelected = computed(() =>
// ── Refresh ─────────────────────────────────────────────── // ── Refresh ───────────────────────────────────────────────
async function refresh(): Promise<void> { async function refresh(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0) await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)
} }
// ── Auto-check timer ────────────────────────────────────── // ── Auto-check timer ──────────────────────────────────────
@ -136,13 +142,13 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
<div class="message-list-header"> <div class="message-list-header">
<h2 class="folder-title truncate">{{ folderName }}</h2> <h2 class="folder-title truncate">{{ folderName }}</h2>
<button <button
v-if="messagesStore.totalCount > 0" v-if="activeUnread > 0 || messagesStore.unreadOnly"
class="message-count" class="message-count"
:class="{ 'unread-active': messagesStore.unreadOnly }" :class="{ 'unread-active': messagesStore.unreadOnly }"
title="Только непрочитанные" title="Только непрочитанные"
@click="messagesStore.unreadOnly = !messagesStore.unreadOnly" @click="messagesStore.toggleUnreadOnly()"
> >
{{ messagesStore.totalCount }} {{ activeUnread }}
</button> </button>
<div class="header-actions"> <div class="header-actions">
<button <button

View file

@ -3,6 +3,7 @@ import { ref, computed } from 'vue'
import type { Folder } from '@shared/types/folder' import type { Folder } from '@shared/types/folder'
import { SpecialFolderRole } from '@shared/types/folder' import { SpecialFolderRole } from '@shared/types/folder'
import { useFoldersStore } from '../../stores/folders.store' import { useFoldersStore } from '../../stores/folders.store'
import { useAccountsStore } from '../../stores/accounts.store'
import AppIcon from '../AppIcon.vue' import AppIcon from '../AppIcon.vue'
import type { IconName } from '../AppIcon.vue' import type { IconName } from '../AppIcon.vue'
@ -12,10 +13,15 @@ const props = defineProps<{
}>() }>()
const foldersStore = useFoldersStore() const foldersStore = useFoldersStore()
const accountsStore = useAccountsStore()
const expanded = ref(true) const expanded = ref(true)
const isActive = computed(() => foldersStore.activeFolderId === props.folder.id) const isActive = computed(() => foldersStore.activeFolderId === props.folder.id)
const hasChildren = computed(() => props.folder.children.length > 0) const hasChildren = computed(() => props.folder.children.length > 0)
const unreadCount = computed(() => {
if (!accountsStore.activeAccountId) return 0
return foldersStore.getFolderUnread(accountsStore.activeAccountId, props.folder.id)
})
const folderIcon = computed((): IconName => { const folderIcon = computed((): IconName => {
switch (props.folder.role) { switch (props.folder.role) {
@ -59,8 +65,8 @@ function toggleExpand(event: Event): void {
<AppIcon :name="folderIcon" :size="14" class="folder-icon" /> <AppIcon :name="folderIcon" :size="14" class="folder-icon" />
<span class="folder-name truncate">{{ folder.name }}</span> <span class="folder-name truncate">{{ folder.name }}</span>
<span v-if="folder.unreadCount > 0" class="unread-badge"> <span v-if="unreadCount > 0" class="unread-badge">
{{ folder.unreadCount }} {{ unreadCount }}
</span> </span>
</button> </button>
@ -158,12 +164,33 @@ function toggleExpand(event: Event): void {
.unread-badge { .unread-badge {
font-size: 10px; font-size: 10px;
font-weight: 700; font-weight: 700;
color: #fff; color: rgba(255, 255, 255, 0.92);
padding: 1px 5px; padding: 0 6px;
min-height: 18px;
line-height: 18px;
border-radius: var(--radius-full); border-radius: var(--radius-full);
background: var(--danger); background: rgba(210, 45, 45, 0.55);
border: 1px solid rgba(255, 100, 100, 0.3);
box-shadow:
inset 0 1px 0 rgba(255, 160, 160, 0.18),
0 1px 5px rgba(180, 30, 30, 0.3);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
flex-shrink: 0; flex-shrink: 0;
min-width: 18px; min-width: 18px;
text-align: center; text-align: center;
transition: background var(--transition-fast), box-shadow var(--transition-fast);
}
.folder-item:hover .unread-badge {
background: rgba(210, 45, 45, 0.7);
box-shadow:
inset 0 1px 0 rgba(255, 160, 160, 0.22),
0 2px 8px rgba(180, 30, 30, 0.4);
}
.folder-item.active .unread-badge {
background: rgba(200, 40, 40, 0.65);
border-color: rgba(255, 100, 100, 0.4);
} }
</style> </style>

View file

@ -13,6 +13,10 @@ export const useFoldersStore = defineStore('folders', () => {
const activeFolderId = ref<string | null>(null) const activeFolderId = ref<string | null>(null)
const loading = ref(false) const loading = ref(false)
// Плоский счётчик непрочитанных: ключ `${accountId}:${folderId}`
// Хранится отдельно от дерева — гарантированно реактивен
const unreadCounts = ref<Record<string, number>>({})
const folders = computed(() => { const folders = computed(() => {
if (!accountsStore.activeAccountId) return [] if (!accountsStore.activeAccountId) return []
return foldersByAccount.value[accountsStore.activeAccountId] ?? [] return foldersByAccount.value[accountsStore.activeAccountId] ?? []
@ -27,6 +31,7 @@ export const useFoldersStore = defineStore('folders', () => {
try { try {
const result = await invoke('folders:list', { accountId }) const result = await invoke('folders:list', { accountId })
foldersByAccount.value[accountId] = result.folders foldersByAccount.value[accountId] = result.folders
initUnreadCounts(accountId, result.folders)
// Auto-select inbox // Auto-select inbox
const inbox = findFolderByRole(result.folders, SpecialFolderRole.Inbox) const inbox = findFolderByRole(result.folders, SpecialFolderRole.Inbox)
@ -44,6 +49,34 @@ export const useFoldersStore = defineStore('folders', () => {
activeFolderId.value = folderId activeFolderId.value = folderId
} }
function initUnreadCounts(accountId: string, folders: Folder[]): void {
for (const f of folders) {
unreadCounts.value[`${accountId}:${f.id}`] = f.unreadCount
if (f.children.length > 0) initUnreadCounts(accountId, f.children)
}
}
function updateFolderUnread(accountId: string, folderId: string, delta: number): void {
const key = `${accountId}:${folderId}`
const current = unreadCounts.value[key] ?? 0
unreadCounts.value[key] = Math.max(0, current + delta)
}
function setFolderUnread(accountId: string, folderId: string, count: number): void {
unreadCounts.value[`${accountId}:${folderId}`] = Math.max(0, count)
}
async function refreshUnreadCounts(accountId: string): Promise<void> {
const result = await invoke('folders:list', { accountId })
foldersByAccount.value[accountId] = result.folders
initUnreadCounts(accountId, result.folders)
// activeFolderId не меняем
}
function getFolderUnread(accountId: string, folderId: string): number {
return unreadCounts.value[`${accountId}:${folderId}`] ?? 0
}
// Auto-load folders when active account changes // Auto-load folders when active account changes
watch( watch(
() => accountsStore.activeAccountId, () => accountsStore.activeAccountId,
@ -68,14 +101,20 @@ export const useFoldersStore = defineStore('folders', () => {
return { return {
foldersByAccount, foldersByAccount,
folders, folders,
unreadCounts,
activeFolderId, activeFolderId,
activeFolder, activeFolder,
loading, loading,
loadFolders, loadFolders,
setActiveFolder refreshUnreadCounts,
setActiveFolder,
updateFolderUnread,
setFolderUnread,
getFolderUnread
} }
}) })
function findFolderById(folders: Folder[], id: string | null): Folder | null { function findFolderById(folders: Folder[], id: string | null): Folder | null {
if (!id) return null if (!id) return null
for (const f of folders) { for (const f of folders) {

View file

@ -58,13 +58,26 @@ export const useMessagesStore = defineStore('messages', () => {
accountId, accountId,
folderId, folderId,
offset, offset,
limit: PAGE_SIZE limit: PAGE_SIZE,
unseenOnly: unreadOnly.value
}) })
if (offset === 0) { if (offset === 0) {
messages.value = result.messages messages.value = result.messages
// Предзагрузка тел первых 10 писем в фоне if (unreadOnly.value) {
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600) // result.total — это точное число непрочитанных из SEARCH UNSEEN
foldersStore.setFolderUnread(accountId, folderId, result.total)
} else if (result.messages.length >= result.total) {
// Все письма загружены — считаем точно из флагов
const exactUnread = result.messages.filter((m) => !m.flags.seen).length
foldersStore.setFolderUnread(accountId, folderId, exactUnread)
}
// Для частичной загрузки не трогаем счётчик — он уже выставлен через IMAP STATUS
// Предзагрузка тел первых 10 писем в фоне (только в обычном режиме)
if (!unreadOnly.value) {
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
}
} else { } else {
messages.value.push(...result.messages) messages.value.push(...result.messages)
} }
@ -120,6 +133,7 @@ export const useMessagesStore = defineStore('messages', () => {
flags: { seen: true } flags: { seen: true }
}) })
msg.flags.seen = true msg.flags.seen = true
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
} }
return return
} }
@ -144,6 +158,7 @@ export const useMessagesStore = defineStore('messages', () => {
flags: { seen: true } flags: { seen: true }
}) })
msg.flags.seen = true msg.flags.seen = true
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
} }
} finally { } finally {
loadingBody.value = false loadingBody.value = false
@ -174,9 +189,18 @@ export const useMessagesStore = defineStore('messages', () => {
selectedIds.value = new Set() selectedIds.value = new Set()
} }
async function toggleUnreadOnly(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
unreadOnly.value = !unreadOnly.value
messages.value = []
totalCount.value = 0
await loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
}
async function deleteSelected(): Promise<void> { async function deleteSelected(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
const ids = [...selectedIds.value] const ids = [...selectedIds.value]
const unreadDelta = messages.value.filter((m) => selectedIds.value.has(m.id) && !m.flags.seen).length
await invoke('messages:delete', { await invoke('messages:delete', {
accountId: accountsStore.activeAccountId, accountId: accountsStore.activeAccountId,
folderId: foldersStore.activeFolderId, folderId: foldersStore.activeFolderId,
@ -184,6 +208,9 @@ export const useMessagesStore = defineStore('messages', () => {
}) })
messages.value = messages.value.filter((m) => !selectedIds.value.has(m.id)) messages.value = messages.value.filter((m) => !selectedIds.value.has(m.id))
totalCount.value = Math.max(0, totalCount.value - ids.length) totalCount.value = Math.max(0, totalCount.value - ids.length)
if (unreadDelta > 0) {
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -unreadDelta)
}
if (selectedMessageId.value && selectedIds.value.has(selectedMessageId.value)) { if (selectedMessageId.value && selectedIds.value.has(selectedMessageId.value)) {
clearSelection() clearSelection()
} }
@ -192,6 +219,8 @@ export const useMessagesStore = defineStore('messages', () => {
async function deleteOne(messageId: string): Promise<void> { async function deleteOne(messageId: string): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
const msg = messages.value.find((m) => m.id === messageId)
const wasUnread = msg && !msg.flags.seen
await invoke('messages:delete', { await invoke('messages:delete', {
accountId: accountsStore.activeAccountId, accountId: accountsStore.activeAccountId,
folderId: foldersStore.activeFolderId, folderId: foldersStore.activeFolderId,
@ -199,6 +228,9 @@ export const useMessagesStore = defineStore('messages', () => {
}) })
messages.value = messages.value.filter((m) => m.id !== messageId) messages.value = messages.value.filter((m) => m.id !== messageId)
totalCount.value = Math.max(0, totalCount.value - 1) totalCount.value = Math.max(0, totalCount.value - 1)
if (wasUnread) {
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
}
if (selectedMessageId.value === messageId) clearSelection() if (selectedMessageId.value === messageId) clearSelection()
} }
@ -214,6 +246,11 @@ export const useMessagesStore = defineStore('messages', () => {
flags: { seen: newSeen } flags: { seen: newSeen }
}) })
msg.flags.seen = newSeen msg.flags.seen = newSeen
foldersStore.updateFolderUnread(
accountsStore.activeAccountId,
foldersStore.activeFolderId,
newSeen ? -1 : 1
)
} }
async function toggleFlag(messageId: string): Promise<void> { async function toggleFlag(messageId: string): Promise<void> {
@ -251,6 +288,7 @@ export const useMessagesStore = defineStore('messages', () => {
async function markSelectedAsRead(): Promise<void> { async function markSelectedAsRead(): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
const ids = [...selectedIds.value] const ids = [...selectedIds.value]
const unreadDelta = messages.value.filter((m) => selectedIds.value.has(m.id) && !m.flags.seen).length
await invoke('messages:setFlags', { await invoke('messages:setFlags', {
accountId: accountsStore.activeAccountId, accountId: accountsStore.activeAccountId,
folderId: foldersStore.activeFolderId, folderId: foldersStore.activeFolderId,
@ -258,9 +296,10 @@ export const useMessagesStore = defineStore('messages', () => {
flags: { seen: true } flags: { seen: true }
}) })
for (const msg of messages.value) { for (const msg of messages.value) {
if (selectedIds.value.has(msg.id)) { if (selectedIds.value.has(msg.id)) msg.flags.seen = true
msg.flags.seen = true }
} if (unreadDelta > 0) {
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -unreadDelta)
} }
selectedIds.value = new Set() selectedIds.value = new Set()
} }
@ -289,6 +328,9 @@ export const useMessagesStore = defineStore('messages', () => {
messages.value.unshift(data.envelope) messages.value.unshift(data.envelope)
totalCount.value++ totalCount.value++
} }
if (!data.envelope.flags.seen) {
foldersStore.updateFolderUnread(data.accountId, data.folderId, 1)
}
}) })
return { return {
@ -308,6 +350,7 @@ export const useMessagesStore = defineStore('messages', () => {
toggleSelect, toggleSelect,
selectAll, selectAll,
clearSelected, clearSelected,
toggleUnreadOnly,
deleteSelected, deleteSelected,
markSelectedAsRead, markSelectedAsRead,
deleteOne, deleteOne,

View file

@ -9,11 +9,13 @@ export interface MessageListOptions {
folderId: string folderId: string
offset: number offset: number
limit: number limit: number
unseenOnly?: boolean
} }
export interface MessageListResult { export interface MessageListResult {
messages: MessageEnvelope[] messages: MessageEnvelope[]
total: number total: number
unseen: number
} }
export interface IEmailProvider { export interface IEmailProvider {