Merge feature/unread-badges: бейджи непрочитанных в сайдбаре и заголовке
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
e779c23abd
8 changed files with 191 additions and 23 deletions
|
|
@ -2,8 +2,8 @@ import { registerHandler } from './registry'
|
|||
import type { AccountManager } from '../services/account-manager'
|
||||
|
||||
export function registerMessageHandlers(manager: AccountManager): void {
|
||||
registerHandler('messages:list', async ({ accountId, folderId, offset, limit }) => {
|
||||
return manager.listMessages(accountId, folderId, offset, limit)
|
||||
registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
|
||||
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
|
||||
})
|
||||
|
||||
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
||||
|
|
|
|||
|
|
@ -69,20 +69,43 @@ export class ImapProvider implements IEmailProvider {
|
|||
// listTree() returns { root: true, folders: ImapMailbox[] }
|
||||
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||
const folders = this.convertMailboxArray(tree.folders ?? [])
|
||||
await this.populateUnreadCounts(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> {
|
||||
const lock = await this.client.getMailboxLock(options.folderId)
|
||||
try {
|
||||
if (options.unseenOnly) {
|
||||
return await this.listUnseenMessages(options)
|
||||
}
|
||||
|
||||
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
|
||||
const end = Math.max(1, total - options.offset)
|
||||
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[] = []
|
||||
|
||||
|
|
@ -98,16 +121,43 @@ export class ImapProvider implements IEmailProvider {
|
|||
// Newest first
|
||||
messages.reverse()
|
||||
|
||||
return { messages, total }
|
||||
return { messages, total, unseen: 0 }
|
||||
} finally {
|
||||
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> {
|
||||
const lock = await this.client.getMailboxLock(folderId)
|
||||
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 })
|
||||
if (!download) {
|
||||
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
|
||||
|
|
|
|||
|
|
@ -125,10 +125,11 @@ export class AccountManager {
|
|||
accountId: string,
|
||||
folderId: string,
|
||||
offset: number,
|
||||
limit: number
|
||||
limit: number,
|
||||
unseenOnly = false
|
||||
): Promise<MessageListResult> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.listMessages({ folderId, offset, limit })
|
||||
return provider.listMessages({ folderId, offset, limit, unseenOnly })
|
||||
}
|
||||
|
||||
async fetchMessageBody(
|
||||
|
|
|
|||
|
|
@ -16,6 +16,10 @@ const selectMode = ref(false)
|
|||
|
||||
const folderName = computed(() => foldersStore.activeFolder?.name ?? '')
|
||||
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(() =>
|
||||
messagesStore.filteredMessages.length > 0 &&
|
||||
messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id))
|
||||
|
|
@ -24,7 +28,9 @@ const allVisibleSelected = computed(() =>
|
|||
// ── Refresh ───────────────────────────────────────────────
|
||||
async function refresh(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
|
||||
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
||||
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)
|
||||
}
|
||||
|
||||
// ── Auto-check timer ──────────────────────────────────────
|
||||
|
|
@ -136,13 +142,13 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
|||
<div class="message-list-header">
|
||||
<h2 class="folder-title truncate">{{ folderName }}</h2>
|
||||
<button
|
||||
v-if="messagesStore.totalCount > 0"
|
||||
v-if="activeUnread > 0 || messagesStore.unreadOnly"
|
||||
class="message-count"
|
||||
:class="{ 'unread-active': messagesStore.unreadOnly }"
|
||||
title="Только непрочитанные"
|
||||
@click="messagesStore.unreadOnly = !messagesStore.unreadOnly"
|
||||
@click="messagesStore.toggleUnreadOnly()"
|
||||
>
|
||||
{{ messagesStore.totalCount }}
|
||||
{{ activeUnread }}
|
||||
</button>
|
||||
<div class="header-actions">
|
||||
<button
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { ref, computed } from 'vue'
|
|||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import { useFoldersStore } from '../../stores/folders.store'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import AppIcon from '../AppIcon.vue'
|
||||
import type { IconName } from '../AppIcon.vue'
|
||||
|
||||
|
|
@ -12,10 +13,15 @@ const props = defineProps<{
|
|||
}>()
|
||||
|
||||
const foldersStore = useFoldersStore()
|
||||
const accountsStore = useAccountsStore()
|
||||
const expanded = ref(true)
|
||||
|
||||
const isActive = computed(() => foldersStore.activeFolderId === props.folder.id)
|
||||
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 => {
|
||||
switch (props.folder.role) {
|
||||
|
|
@ -59,8 +65,8 @@ function toggleExpand(event: Event): void {
|
|||
|
||||
<AppIcon :name="folderIcon" :size="14" class="folder-icon" />
|
||||
<span class="folder-name truncate">{{ folder.name }}</span>
|
||||
<span v-if="folder.unreadCount > 0" class="unread-badge">
|
||||
{{ folder.unreadCount }}
|
||||
<span v-if="unreadCount > 0" class="unread-badge">
|
||||
{{ unreadCount }}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
|
|
@ -158,12 +164,33 @@ function toggleExpand(event: Event): void {
|
|||
.unread-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
padding: 1px 5px;
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
padding: 0 6px;
|
||||
min-height: 18px;
|
||||
line-height: 18px;
|
||||
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;
|
||||
min-width: 18px;
|
||||
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>
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ export const useFoldersStore = defineStore('folders', () => {
|
|||
const activeFolderId = ref<string | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
// Плоский счётчик непрочитанных: ключ `${accountId}:${folderId}`
|
||||
// Хранится отдельно от дерева — гарантированно реактивен
|
||||
const unreadCounts = ref<Record<string, number>>({})
|
||||
|
||||
const folders = computed(() => {
|
||||
if (!accountsStore.activeAccountId) return []
|
||||
return foldersByAccount.value[accountsStore.activeAccountId] ?? []
|
||||
|
|
@ -27,6 +31,7 @@ export const useFoldersStore = defineStore('folders', () => {
|
|||
try {
|
||||
const result = await invoke('folders:list', { accountId })
|
||||
foldersByAccount.value[accountId] = result.folders
|
||||
initUnreadCounts(accountId, result.folders)
|
||||
|
||||
// Auto-select inbox
|
||||
const inbox = findFolderByRole(result.folders, SpecialFolderRole.Inbox)
|
||||
|
|
@ -44,6 +49,34 @@ export const useFoldersStore = defineStore('folders', () => {
|
|||
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
|
||||
watch(
|
||||
() => accountsStore.activeAccountId,
|
||||
|
|
@ -68,14 +101,20 @@ export const useFoldersStore = defineStore('folders', () => {
|
|||
return {
|
||||
foldersByAccount,
|
||||
folders,
|
||||
unreadCounts,
|
||||
activeFolderId,
|
||||
activeFolder,
|
||||
loading,
|
||||
loadFolders,
|
||||
setActiveFolder
|
||||
refreshUnreadCounts,
|
||||
setActiveFolder,
|
||||
updateFolderUnread,
|
||||
setFolderUnread,
|
||||
getFolderUnread
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
function findFolderById(folders: Folder[], id: string | null): Folder | null {
|
||||
if (!id) return null
|
||||
for (const f of folders) {
|
||||
|
|
|
|||
|
|
@ -58,13 +58,26 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
accountId,
|
||||
folderId,
|
||||
offset,
|
||||
limit: PAGE_SIZE
|
||||
limit: PAGE_SIZE,
|
||||
unseenOnly: unreadOnly.value
|
||||
})
|
||||
|
||||
if (offset === 0) {
|
||||
messages.value = result.messages
|
||||
// Предзагрузка тел первых 10 писем в фоне
|
||||
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
|
||||
if (unreadOnly.value) {
|
||||
// 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 {
|
||||
messages.value.push(...result.messages)
|
||||
}
|
||||
|
|
@ -120,6 +133,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
flags: { seen: true }
|
||||
})
|
||||
msg.flags.seen = true
|
||||
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
@ -144,6 +158,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
flags: { seen: true }
|
||||
})
|
||||
msg.flags.seen = true
|
||||
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
|
||||
}
|
||||
} finally {
|
||||
loadingBody.value = false
|
||||
|
|
@ -174,9 +189,18 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
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> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||
const ids = [...selectedIds.value]
|
||||
const unreadDelta = messages.value.filter((m) => selectedIds.value.has(m.id) && !m.flags.seen).length
|
||||
await invoke('messages:delete', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
|
|
@ -184,6 +208,9 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
})
|
||||
messages.value = messages.value.filter((m) => !selectedIds.value.has(m.id))
|
||||
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)) {
|
||||
clearSelection()
|
||||
}
|
||||
|
|
@ -192,6 +219,8 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
|
||||
async function deleteOne(messageId: string): Promise<void> {
|
||||
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', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
|
|
@ -199,6 +228,9 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
})
|
||||
messages.value = messages.value.filter((m) => m.id !== messageId)
|
||||
totalCount.value = Math.max(0, totalCount.value - 1)
|
||||
if (wasUnread) {
|
||||
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -1)
|
||||
}
|
||||
if (selectedMessageId.value === messageId) clearSelection()
|
||||
}
|
||||
|
||||
|
|
@ -214,6 +246,11 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
flags: { seen: newSeen }
|
||||
})
|
||||
msg.flags.seen = newSeen
|
||||
foldersStore.updateFolderUnread(
|
||||
accountsStore.activeAccountId,
|
||||
foldersStore.activeFolderId,
|
||||
newSeen ? -1 : 1
|
||||
)
|
||||
}
|
||||
|
||||
async function toggleFlag(messageId: string): Promise<void> {
|
||||
|
|
@ -251,6 +288,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
async function markSelectedAsRead(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||
const ids = [...selectedIds.value]
|
||||
const unreadDelta = messages.value.filter((m) => selectedIds.value.has(m.id) && !m.flags.seen).length
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
|
|
@ -258,9 +296,10 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
flags: { seen: true }
|
||||
})
|
||||
for (const msg of messages.value) {
|
||||
if (selectedIds.value.has(msg.id)) {
|
||||
msg.flags.seen = true
|
||||
}
|
||||
if (selectedIds.value.has(msg.id)) msg.flags.seen = true
|
||||
}
|
||||
if (unreadDelta > 0) {
|
||||
foldersStore.updateFolderUnread(accountsStore.activeAccountId, foldersStore.activeFolderId, -unreadDelta)
|
||||
}
|
||||
selectedIds.value = new Set()
|
||||
}
|
||||
|
|
@ -289,6 +328,9 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
messages.value.unshift(data.envelope)
|
||||
totalCount.value++
|
||||
}
|
||||
if (!data.envelope.flags.seen) {
|
||||
foldersStore.updateFolderUnread(data.accountId, data.folderId, 1)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
|
|
@ -308,6 +350,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
toggleSelect,
|
||||
selectAll,
|
||||
clearSelected,
|
||||
toggleUnreadOnly,
|
||||
deleteSelected,
|
||||
markSelectedAsRead,
|
||||
deleteOne,
|
||||
|
|
|
|||
|
|
@ -9,11 +9,13 @@ export interface MessageListOptions {
|
|||
folderId: string
|
||||
offset: number
|
||||
limit: number
|
||||
unseenOnly?: boolean
|
||||
}
|
||||
|
||||
export interface MessageListResult {
|
||||
messages: MessageEnvelope[]
|
||||
total: number
|
||||
unseen: number
|
||||
}
|
||||
|
||||
export interface IEmailProvider {
|
||||
|
|
|
|||
Loading…
Reference in a new issue