Merge branch 'feature/search-and-notifications'
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
823f6e5b8d
15 changed files with 1010 additions and 42 deletions
|
|
@ -30,6 +30,11 @@ function createWindow(): BrowserWindow {
|
||||||
|
|
||||||
accountManager.setMainWindow(mainWindow)
|
accountManager.setMainWindow(mainWindow)
|
||||||
|
|
||||||
|
// Разрешаем Web Notifications API из renderer
|
||||||
|
mainWindow.webContents.session.setPermissionRequestHandler((_wc, permission, callback) => {
|
||||||
|
callback(permission === 'notifications')
|
||||||
|
})
|
||||||
|
|
||||||
globalShortcut.register('F12', () => {
|
globalShortcut.register('F12', () => {
|
||||||
mainWindow.webContents.toggleDevTools()
|
mainWindow.webContents.toggleDevTools()
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,14 @@ export function registerMessageHandlers(manager: AccountManager): void {
|
||||||
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
|
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
registerHandler('messages:poll', async ({ accountId }) => {
|
||||||
|
await manager.pollNewMessages(accountId)
|
||||||
|
})
|
||||||
|
|
||||||
|
registerHandler('messages:search', async ({ accountId, query, limit }) => {
|
||||||
|
return manager.searchMessages(accountId, query, limit)
|
||||||
|
})
|
||||||
|
|
||||||
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
||||||
return manager.fetchMessageBody(accountId, folderId, messageId)
|
return manager.fetchMessageBody(accountId, folderId, messageId)
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -187,6 +187,9 @@ export class ExchangeProvider implements IEmailProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async pollNewMessages(): Promise<void> { /* Exchange использует свой polling через onNewMail */ }
|
||||||
|
async searchMessages(_query: string, _limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> { return [] }
|
||||||
|
|
||||||
private detectRole(name: string): SpecialFolderRole {
|
private detectRole(name: string): SpecialFolderRole {
|
||||||
const n = name.toLowerCase()
|
const n = name.toLowerCase()
|
||||||
if (n === 'inbox') return SpecialFolderRole.Inbox
|
if (n === 'inbox') return SpecialFolderRole.Inbox
|
||||||
|
|
|
||||||
|
|
@ -174,6 +174,29 @@ export class GmailProvider implements IEmailProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async pollNewMessages(): Promise<void> { /* Gmail использует свой polling через onNewMail */ }
|
||||||
|
|
||||||
|
async searchMessages(query: string, limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> {
|
||||||
|
try {
|
||||||
|
const res = await this.gmail.users.messages.list({
|
||||||
|
userId: 'me',
|
||||||
|
q: query,
|
||||||
|
maxResults: limit
|
||||||
|
})
|
||||||
|
const items = res.data.messages ?? []
|
||||||
|
const results: import('@shared/types/message').MessageEnvelope[] = []
|
||||||
|
for (const item of items) {
|
||||||
|
if (!item.id) continue
|
||||||
|
const msg = await this.gmail.users.messages.get({ userId: 'me', id: item.id, format: 'metadata',
|
||||||
|
metadataHeaders: ['Subject', 'From', 'To', 'Date'] })
|
||||||
|
results.push(this.convertMessage(msg.data, 'INBOX'))
|
||||||
|
}
|
||||||
|
return results
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private detectRole(labelId: string): SpecialFolderRole {
|
private detectRole(labelId: string): SpecialFolderRole {
|
||||||
switch (labelId) {
|
switch (labelId) {
|
||||||
case 'INBOX': return SpecialFolderRole.Inbox
|
case 'INBOX': return SpecialFolderRole.Inbox
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,8 @@ export class ImapProvider implements IEmailProvider {
|
||||||
private client: ImapFlow
|
private client: ImapFlow
|
||||||
private connected = false
|
private connected = false
|
||||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||||
|
// folderId → last known unseen count for polling
|
||||||
|
private lastUnseenCount = new Map<string, number>()
|
||||||
|
|
||||||
constructor(private config: AccountConfig) {
|
constructor(private config: AccountConfig) {
|
||||||
const creds = config.credentials as ImapCredentials
|
const creds = config.credentials as ImapCredentials
|
||||||
|
|
@ -159,7 +161,7 @@ export class ImapProvider implements IEmailProvider {
|
||||||
try {
|
try {
|
||||||
// imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
|
// 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?.content) {
|
||||||
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
|
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -251,12 +253,13 @@ export class ImapProvider implements IEmailProvider {
|
||||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||||
this.newMailCallback = callback
|
this.newMailCallback = callback
|
||||||
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
|
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
|
||||||
if (this.newMailCallback && data.count > data.prevCount) {
|
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
|
||||||
|
if (this.newMailCallback && data.prevCount > 0 && data.count > data.prevCount) {
|
||||||
this.newMailCallback(data.path, {
|
this.newMailCallback(data.path, {
|
||||||
id: '',
|
id: '',
|
||||||
folderId: data.path,
|
folderId: data.path,
|
||||||
subject: 'New message',
|
subject: 'Новое сообщение',
|
||||||
from: { name: '', email: '' },
|
from: { name: 'Новое письмо', email: '' },
|
||||||
to: [],
|
to: [],
|
||||||
cc: [],
|
cc: [],
|
||||||
date: new Date().toISOString(),
|
date: new Date().toISOString(),
|
||||||
|
|
@ -273,6 +276,116 @@ export class ImapProvider implements IEmailProvider {
|
||||||
this.client.removeAllListeners('exists')
|
this.client.removeAllListeners('exists')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
|
||||||
|
const results: MessageEnvelope[] = []
|
||||||
|
// Не ловим ошибки здесь — они должны попасть в withAutoReconnect (AccountManager)
|
||||||
|
// для переподключения при NoConnection и прочих сетевых сбоях
|
||||||
|
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||||
|
await this.searchFolderTree(tree.folders ?? [], query, limit, results)
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
private shouldSkipFolder(folder: ImapMailbox): boolean {
|
||||||
|
const n = folder.name.toLowerCase()
|
||||||
|
const p = (folder.path ?? '').toLowerCase()
|
||||||
|
return (
|
||||||
|
n === 'trash' || n === 'deleted items' || n === 'deleted messages' ||
|
||||||
|
n === 'spam' || n === 'junk' || n === 'junk e-mail' ||
|
||||||
|
p.includes('[gmail]/trash') || p.includes('[gmail]/spam')
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async searchFolderTree(
|
||||||
|
folders: ImapMailbox[],
|
||||||
|
query: string,
|
||||||
|
limit: number,
|
||||||
|
results: MessageEnvelope[]
|
||||||
|
): Promise<void> {
|
||||||
|
for (const folder of folders) {
|
||||||
|
if (results.length >= limit) break
|
||||||
|
if (this.shouldSkipFolder(folder)) {
|
||||||
|
if (folder.folders?.length && results.length < limit) {
|
||||||
|
await this.searchFolderTree(folder.folders, query, limit, results)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let lock: Awaited<ReturnType<typeof this.client.getMailboxLock>> | null = null
|
||||||
|
try {
|
||||||
|
lock = await this.client.getMailboxLock(folder.path)
|
||||||
|
|
||||||
|
// SUBJECT + FROM — серверный поиск (быстрее, чем TEXT по телу)
|
||||||
|
const rawSubject = await this.client.search({ subject: query }, { uid: true })
|
||||||
|
const rawFrom = await this.client.search({ from: query }, { uid: true })
|
||||||
|
const subjectUids = Array.isArray(rawSubject) ? rawSubject : []
|
||||||
|
const fromUids = Array.isArray(rawFrom) ? rawFrom : []
|
||||||
|
|
||||||
|
// Объединяем UIDs без дублей
|
||||||
|
const merged = [...new Set([...subjectUids, ...fromUids])]
|
||||||
|
|
||||||
|
if (merged.length) {
|
||||||
|
const remaining = limit - results.length
|
||||||
|
const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining)
|
||||||
|
for await (const msg of this.client.fetch(sorted.join(','), {
|
||||||
|
uid: true, envelope: true, flags: true, bodyStructure: true
|
||||||
|
}, { uid: true })) {
|
||||||
|
results.push(this.convertMessage(msg, folder.path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[IMAP:search] folder error:', folder?.path, e)
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
lock?.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (folder.folders?.length && results.length < limit) {
|
||||||
|
await this.searchFolderTree(folder.folders, query, limit, results)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async pollNewMessages(): Promise<void> {
|
||||||
|
if (!this.newMailCallback) return
|
||||||
|
try {
|
||||||
|
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||||
|
await this.pollFolderTree(tree.folders ?? [])
|
||||||
|
} catch { /* ignore poll errors */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
|
||||||
|
for (const folder of folders) {
|
||||||
|
try {
|
||||||
|
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null
|
||||||
|
const unseen = status?.unseen ?? 0
|
||||||
|
const prev = this.lastUnseenCount.get(folder.path)
|
||||||
|
this.lastUnseenCount.set(folder.path, unseen)
|
||||||
|
|
||||||
|
if (prev !== undefined && unseen > prev && this.newMailCallback) {
|
||||||
|
// Получаем последнее непрочитанное письмо для уведомления
|
||||||
|
const lock = await this.client.getMailboxLock(folder.path)
|
||||||
|
try {
|
||||||
|
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
|
||||||
|
if (uids?.length) {
|
||||||
|
const latestUid = Math.max(...uids).toString()
|
||||||
|
for await (const msg of this.client.fetch(latestUid, {
|
||||||
|
uid: true, envelope: true, flags: true
|
||||||
|
}, { uid: true })) {
|
||||||
|
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
lock.release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* некоторые папки не поддерживают STATUS */ }
|
||||||
|
|
||||||
|
if (folder.folders?.length) {
|
||||||
|
await this.pollFolderTree(folder.folders)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Private helpers ----
|
// ---- Private helpers ----
|
||||||
|
|
||||||
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
|
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
import { BrowserWindow } from 'electron'
|
import { BrowserWindow, Notification, nativeImage } from 'electron'
|
||||||
|
import { join } from 'node:path'
|
||||||
import type { AccountConfig } from '@shared/types/account'
|
import type { AccountConfig } from '@shared/types/account'
|
||||||
import { AccountType } from '@shared/types/account'
|
import { AccountType } from '@shared/types/account'
|
||||||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
||||||
import type { MessageBody, MessageFlags } from '@shared/types/message'
|
import type { MessageBody, MessageFlags, MessageEnvelope } from '@shared/types/message'
|
||||||
import { ImapProvider } from '../providers/imap.provider'
|
import { ImapProvider } from '../providers/imap.provider'
|
||||||
import { ExchangeProvider } from '../providers/exchange.provider'
|
import { ExchangeProvider } from '../providers/exchange.provider'
|
||||||
import { GmailProvider } from '../providers/gmail.provider'
|
import { GmailProvider } from '../providers/gmail.provider'
|
||||||
|
|
@ -13,6 +14,9 @@ interface AccountStoreSchema {
|
||||||
accounts: Omit<AccountConfig, 'credentials'>[]
|
accounts: Omit<AccountConfig, 'credentials'>[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Коды ошибок imapflow при потере соединения
|
||||||
|
const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'])
|
||||||
|
|
||||||
export class AccountManager {
|
export class AccountManager {
|
||||||
private providers = new Map<string, IEmailProvider>()
|
private providers = new Map<string, IEmailProvider>()
|
||||||
private store: Store<AccountStoreSchema>
|
private store: Store<AccountStoreSchema>
|
||||||
|
|
@ -117,8 +121,22 @@ export class AccountManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
async listFolders(accountId: string): Promise<FolderListResult> {
|
async listFolders(accountId: string): Promise<FolderListResult> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.listFolders()
|
this.getProvider(accountId).listFolders()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async pollNewMessages(accountId: string): Promise<void> {
|
||||||
|
const provider = this.providers.get(accountId)
|
||||||
|
if (provider) await provider.pollNewMessages().catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async searchMessages(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
|
||||||
|
return this.withAutoReconnect(accountId, () => {
|
||||||
|
const provider = this.providers.get(accountId)
|
||||||
|
if (!provider) return Promise.resolve([])
|
||||||
|
return provider.searchMessages(query, limit)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async listMessages(
|
async listMessages(
|
||||||
|
|
@ -128,8 +146,9 @@ export class AccountManager {
|
||||||
limit: number,
|
limit: number,
|
||||||
unseenOnly = false
|
unseenOnly = false
|
||||||
): Promise<MessageListResult> {
|
): Promise<MessageListResult> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.listMessages({ folderId, offset, limit, unseenOnly })
|
this.getProvider(accountId).listMessages({ folderId, offset, limit, unseenOnly })
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetchMessageBody(
|
async fetchMessageBody(
|
||||||
|
|
@ -137,8 +156,9 @@ export class AccountManager {
|
||||||
folderId: string,
|
folderId: string,
|
||||||
messageId: string
|
messageId: string
|
||||||
): Promise<MessageBody> {
|
): Promise<MessageBody> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.fetchMessageBody(folderId, messageId)
|
this.getProvider(accountId).fetchMessageBody(folderId, messageId)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async downloadAttachment(
|
async downloadAttachment(
|
||||||
|
|
@ -147,8 +167,9 @@ export class AccountManager {
|
||||||
messageId: string,
|
messageId: string,
|
||||||
attachmentId: string
|
attachmentId: string
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.downloadAttachment(folderId, messageId, attachmentId)
|
this.getProvider(accountId).downloadAttachment(folderId, messageId, attachmentId)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateFlags(
|
async updateFlags(
|
||||||
|
|
@ -157,8 +178,9 @@ export class AccountManager {
|
||||||
messageIds: string[],
|
messageIds: string[],
|
||||||
flags: Partial<MessageFlags>
|
flags: Partial<MessageFlags>
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.updateFlags(folderId, messageIds, flags)
|
this.getProvider(accountId).updateFlags(folderId, messageIds, flags)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteMessages(
|
async deleteMessages(
|
||||||
|
|
@ -166,10 +188,51 @@ export class AccountManager {
|
||||||
folderId: string,
|
folderId: string,
|
||||||
messageIds: string[]
|
messageIds: string[]
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.deleteMessages(folderId, messageIds)
|
this.getProvider(accountId).deleteMessages(folderId, messageIds)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Auto-reconnect ──────────────────────────────────────
|
||||||
|
|
||||||
|
private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
|
||||||
|
try {
|
||||||
|
return await fn()
|
||||||
|
} catch (err) {
|
||||||
|
const code = (err as { code?: string }).code ?? ''
|
||||||
|
if (RECONNECT_CODES.has(code)) {
|
||||||
|
await this.reconnectAccount(accountId)
|
||||||
|
return await fn()
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async reconnectAccount(accountId: string): Promise<void> {
|
||||||
|
// Убиваем старый провайдер
|
||||||
|
const old = this.providers.get(accountId)
|
||||||
|
if (old) {
|
||||||
|
old.offNewMail()
|
||||||
|
try { await old.disconnect() } catch { /* уже отвалился */ }
|
||||||
|
this.providers.delete(accountId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const accounts = this.store.get('accounts', [])
|
||||||
|
const accMeta = accounts.find((a) => a.id === accountId)
|
||||||
|
if (!accMeta) throw new Error('Account not found')
|
||||||
|
|
||||||
|
const credRaw = this.credentialStore.get(accountId)
|
||||||
|
if (!credRaw) throw new Error('Credentials not found')
|
||||||
|
|
||||||
|
const config: AccountConfig = { ...accMeta, credentials: JSON.parse(credRaw) }
|
||||||
|
const provider = this.createProvider(config)
|
||||||
|
await provider.connect()
|
||||||
|
this.providers.set(accountId, provider)
|
||||||
|
this.setupNewMailListener(accountId, provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Private helpers ─────────────────────────────────────
|
||||||
|
|
||||||
private getProvider(accountId: string): IEmailProvider {
|
private getProvider(accountId: string): IEmailProvider {
|
||||||
const provider = this.providers.get(accountId)
|
const provider = this.providers.get(accountId)
|
||||||
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
||||||
|
|
@ -194,6 +257,28 @@ export class AccountManager {
|
||||||
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||||||
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Notification.isSupported()) {
|
||||||
|
const from = envelope.from.name || envelope.from.email || 'Новое письмо'
|
||||||
|
const subject = envelope.subject || '(без темы)'
|
||||||
|
const iconPath = join(__dirname, '../../resources/icon.png')
|
||||||
|
const icon = nativeImage.createFromPath(iconPath)
|
||||||
|
|
||||||
|
const n = new Notification({
|
||||||
|
title: from,
|
||||||
|
body: subject,
|
||||||
|
icon: icon.isEmpty() ? undefined : icon,
|
||||||
|
silent: false,
|
||||||
|
})
|
||||||
|
n.on('click', () => {
|
||||||
|
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||||||
|
this.mainWindow.show()
|
||||||
|
this.mainWindow.focus()
|
||||||
|
this.mainWindow.webContents.send('notification:click', { accountId, folderId, messageId: envelope.id })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
n.show()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,8 @@ export type IconName =
|
||||||
| 'envelope'
|
| 'envelope'
|
||||||
| 'refresh'
|
| 'refresh'
|
||||||
| 'threads'
|
| 'threads'
|
||||||
|
| 'search'
|
||||||
|
| 'close'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
name: IconName
|
name: IconName
|
||||||
|
|
@ -89,6 +91,14 @@ const paths: Record<IconName, string> = {
|
||||||
<line x1="13" y1="10" x2="13.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"/>
|
<line x1="17" y1="10" x2="17.01" y2="10" stroke-width="2.5"/>
|
||||||
`,
|
`,
|
||||||
|
search: `
|
||||||
|
<circle cx="11" cy="11" r="8"/>
|
||||||
|
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
||||||
|
`,
|
||||||
|
close: `
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||||
|
`,
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import FolderTree from '../sidebar/FolderTree.vue'
|
||||||
import MessageList from '../messages/MessageList.vue'
|
import MessageList from '../messages/MessageList.vue'
|
||||||
import MessagePreview from '../preview/MessagePreview.vue'
|
import MessagePreview from '../preview/MessagePreview.vue'
|
||||||
import AddAccountDialog from '../accounts/AddAccountDialog.vue'
|
import AddAccountDialog from '../accounts/AddAccountDialog.vue'
|
||||||
|
import NotificationContainer from '../notifications/NotificationContainer.vue'
|
||||||
import AppIcon from '../AppIcon.vue'
|
import AppIcon from '../AppIcon.vue'
|
||||||
import { useAccountsStore } from '../../stores/accounts.store'
|
import { useAccountsStore } from '../../stores/accounts.store'
|
||||||
|
|
||||||
|
|
@ -79,6 +80,8 @@ function stopResize(): void {
|
||||||
@close="showAddAccount = false"
|
@close="showAddAccount = false"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<NotificationContainer />
|
||||||
|
|
||||||
<!-- Пустое состояние: нет аккаунтов -->
|
<!-- Пустое состояние: нет аккаунтов -->
|
||||||
<div v-if="accountsStore.accounts.length === 0 && !accountsStore.loading && !showAddAccount" class="empty-state">
|
<div v-if="accountsStore.accounts.length === 0 && !accountsStore.loading && !showAddAccount" class="empty-state">
|
||||||
<div class="empty-content">
|
<div class="empty-content">
|
||||||
|
|
|
||||||
|
|
@ -1,21 +1,93 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
|
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
|
||||||
import { useMessagesStore } from '../../stores/messages.store'
|
import { useMessagesStore } from '../../stores/messages.store'
|
||||||
import { useFoldersStore } from '../../stores/folders.store'
|
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 { useIpc } from '../../composables/useIpc'
|
||||||
import MessageListItem from './MessageListItem.vue'
|
import MessageListItem from './MessageListItem.vue'
|
||||||
import ThreadListItem from './ThreadListItem.vue'
|
import ThreadListItem from './ThreadListItem.vue'
|
||||||
import AppIcon from '../AppIcon.vue'
|
import AppIcon from '../AppIcon.vue'
|
||||||
import { buildThreads, type Thread } from '../../utils/threading'
|
import { buildThreads, type Thread } from '../../utils/threading'
|
||||||
|
import type { MessageEnvelope } from '@shared/types/message'
|
||||||
|
|
||||||
const messagesStore = useMessagesStore()
|
const messagesStore = useMessagesStore()
|
||||||
const foldersStore = useFoldersStore()
|
const foldersStore = useFoldersStore()
|
||||||
const accountsStore = useAccountsStore()
|
const accountsStore = useAccountsStore()
|
||||||
const settingsStore = useSettingsStore()
|
const settingsStore = useSettingsStore()
|
||||||
|
const { invoke } = useIpc()
|
||||||
|
|
||||||
const selectMode = ref(false)
|
const selectMode = ref(false)
|
||||||
|
|
||||||
|
// ── Search ────────────────────────────────────────────────
|
||||||
|
const searchOpen = ref(false)
|
||||||
|
const searchInputEl = ref<HTMLInputElement | null>(null)
|
||||||
|
const localSearchQuery = ref('')
|
||||||
|
let searchDebounce: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
watch(localSearchQuery, (val) => {
|
||||||
|
if (searchDebounce) clearTimeout(searchDebounce)
|
||||||
|
searchDebounce = setTimeout(() => messagesStore.search(val), 300)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Если поиск очищен извне (смена папки) — сбрасываем localSearchQuery
|
||||||
|
watch(() => messagesStore.isSearchActive, (active) => {
|
||||||
|
if (!active && localSearchQuery.value) {
|
||||||
|
localSearchQuery.value = ''
|
||||||
|
searchOpen.value = false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function openSearch(): void {
|
||||||
|
searchOpen.value = true
|
||||||
|
setTimeout(() => {
|
||||||
|
searchInputEl.value?.removeAttribute('tabindex')
|
||||||
|
searchInputEl.value?.focus()
|
||||||
|
}, 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSearch(): void {
|
||||||
|
searchOpen.value = false
|
||||||
|
localSearchQuery.value = ''
|
||||||
|
searchInputEl.value?.setAttribute('tabindex', '-1')
|
||||||
|
messagesStore.clearSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSearchKeydown(e: KeyboardEvent): void {
|
||||||
|
if (e.key === 'Escape') closeSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectSearchResult(envelope: MessageEnvelope): Promise<void> {
|
||||||
|
foldersStore.setActiveFolder(envelope.folderId)
|
||||||
|
await messagesStore.selectMessage(envelope.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFolderName(folderId: string): string {
|
||||||
|
if (!accountsStore.activeAccountId) return folderId
|
||||||
|
const all = foldersStore.foldersByAccount[accountsStore.activeAccountId] ?? []
|
||||||
|
return findFolderName(all, folderId) ?? folderId
|
||||||
|
}
|
||||||
|
|
||||||
|
function findFolderName(folders: import('@shared/types/folder').Folder[], id: string): string | null {
|
||||||
|
for (const f of folders) {
|
||||||
|
if (f.id === id) return f.name
|
||||||
|
if (f.children.length) {
|
||||||
|
const found = findFolderName(f.children, id)
|
||||||
|
if (found) return found
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function onGlobalKeydown(e: KeyboardEvent): void {
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
|
||||||
|
e.preventDefault()
|
||||||
|
openSearch()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onMounted(() => document.addEventListener('keydown', onGlobalKeydown))
|
||||||
|
onUnmounted(() => document.removeEventListener('keydown', onGlobalKeydown))
|
||||||
|
|
||||||
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(() => {
|
const activeUnread = computed(() => {
|
||||||
|
|
@ -137,6 +209,8 @@ function onExpandAfterLeave(el: Element): void {
|
||||||
// ── Refresh ───────────────────────────────────────────────
|
// ── Refresh ───────────────────────────────────────────────
|
||||||
async function refresh(): Promise<void> {
|
async function refresh(): Promise<void> {
|
||||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||||
|
// Проверяем новые письма во всех папках (для уведомлений)
|
||||||
|
invoke('messages:poll', { accountId: accountsStore.activeAccountId }).catch(() => {})
|
||||||
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
|
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
|
||||||
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
||||||
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)
|
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)
|
||||||
|
|
@ -253,6 +327,8 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
<div class="message-list-container">
|
<div class="message-list-container">
|
||||||
<!-- Заголовок -->
|
<!-- Заголовок -->
|
||||||
<div class="message-list-header">
|
<div class="message-list-header">
|
||||||
|
<!-- Обычный контент: гасится при поиске -->
|
||||||
|
<div class="header-normal" :class="{ 'is-hidden': searchOpen }">
|
||||||
<h2 class="folder-title truncate">{{ folderName }}</h2>
|
<h2 class="folder-title truncate">{{ folderName }}</h2>
|
||||||
<button
|
<button
|
||||||
v-if="activeUnread > 0 || messagesStore.unreadOnly"
|
v-if="activeUnread > 0 || messagesStore.unreadOnly"
|
||||||
|
|
@ -279,6 +355,35 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Поисковая панель: выезжает из правого угла -->
|
||||||
|
<div
|
||||||
|
class="search-pill"
|
||||||
|
:class="{ 'search-pill--open': searchOpen }"
|
||||||
|
@click="!searchOpen && openSearch()"
|
||||||
|
>
|
||||||
|
<span class="search-pill-icon">
|
||||||
|
<AppIcon name="search" :size="13" />
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
ref="searchInputEl"
|
||||||
|
class="search-pill-input"
|
||||||
|
placeholder="Поиск по письмам..."
|
||||||
|
v-model="localSearchQuery"
|
||||||
|
tabindex="-1"
|
||||||
|
@keydown="onSearchKeydown"
|
||||||
|
/>
|
||||||
|
<div v-if="messagesStore.searchLoading" class="spinner-sm search-pill-spinner" />
|
||||||
|
<button
|
||||||
|
v-if="searchOpen"
|
||||||
|
class="search-pill-close"
|
||||||
|
v-tooltip="'Закрыть (Esc)'"
|
||||||
|
@click.stop="closeSearch"
|
||||||
|
>
|
||||||
|
<AppIcon name="close" :size="10" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Pull-to-refresh индикатор (всегда в DOM, высота = 0 в обычном состоянии) -->
|
<!-- Pull-to-refresh индикатор (всегда в DOM, высота = 0 в обычном состоянии) -->
|
||||||
<div
|
<div
|
||||||
class="pull-indicator-wrap"
|
class="pull-indicator-wrap"
|
||||||
|
|
@ -301,9 +406,38 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Результаты поиска -->
|
||||||
|
<template v-if="messagesStore.isSearchActive">
|
||||||
|
<div v-if="messagesStore.searchLoading && messagesStore.searchResults.length === 0" class="loading-state">
|
||||||
|
<div class="spinner" />
|
||||||
|
<span>Поиск...</span>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="messagesStore.searchResults.length === 0" class="empty-state">
|
||||||
|
<AppIcon name="search" :size="28" style="opacity:0.25" />
|
||||||
|
<span>Ничего не найдено</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="message-list search-results-list">
|
||||||
|
<div class="search-results-count">{{ messagesStore.searchResults.length }} результатов</div>
|
||||||
|
<div
|
||||||
|
v-for="result in messagesStore.searchResults"
|
||||||
|
:key="`${result.folderId}:${result.id}`"
|
||||||
|
class="search-result-item"
|
||||||
|
:class="{ selected: messagesStore.selectedMessageId === result.id }"
|
||||||
|
@click="selectSearchResult(result)"
|
||||||
|
>
|
||||||
|
<div class="search-result-row">
|
||||||
|
<span class="search-result-from truncate">{{ result.from.name || result.from.email }}</span>
|
||||||
|
<span class="search-result-date">{{ result.date ? new Date(result.date).toLocaleDateString('ru', { day:'numeric', month:'short' }) : '' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="search-result-subject truncate">{{ result.subject || '(без темы)' }}</div>
|
||||||
|
<span class="search-result-folder">{{ getFolderName(result.folderId) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Загрузка -->
|
<!-- Загрузка -->
|
||||||
<div
|
<div
|
||||||
v-if="messagesStore.loading && messagesStore.messages.length === 0"
|
v-else-if="messagesStore.loading && messagesStore.messages.length === 0"
|
||||||
class="loading-state"
|
class="loading-state"
|
||||||
>
|
>
|
||||||
<div class="spinner" />
|
<div class="spinner" />
|
||||||
|
|
@ -443,8 +577,8 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
.message-list-header {
|
.message-list-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
/* padding-right: чуть больше чтобы кнопка выбора не уходила под пилюлю */
|
||||||
padding: 10px 12px;
|
padding: 10px 46px 10px 12px;
|
||||||
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
|
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
|
||||||
box-shadow:
|
box-shadow:
|
||||||
inset 0 1px 0 rgba(255, 255, 255, 0.10),
|
inset 0 1px 0 rgba(255, 255, 255, 0.10),
|
||||||
|
|
@ -457,6 +591,7 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
rgba(12, 12, 20, 0.65);
|
rgba(12, 12, 20, 0.65);
|
||||||
backdrop-filter: blur(24px) saturate(1.6);
|
backdrop-filter: blur(24px) saturate(1.6);
|
||||||
-webkit-backdrop-filter: blur(24px) saturate(1.6);
|
-webkit-backdrop-filter: blur(24px) saturate(1.6);
|
||||||
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
.folder-title {
|
.folder-title {
|
||||||
|
|
@ -941,4 +1076,226 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Анимация раскрытия управляется JS-хуками через scrollHeight */
|
/* Анимация раскрытия управляется JS-хуками через scrollHeight */
|
||||||
|
|
||||||
|
/* ── Search pill ─────────────────────────────────────────── */
|
||||||
|
.header-normal {
|
||||||
|
display: contents; /* дети становятся детьми хедера напрямую */
|
||||||
|
transition: opacity 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fade-out когда поиск открыт */
|
||||||
|
.header-normal.is-hidden > * {
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
transition: opacity 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-normal > * {
|
||||||
|
transition: opacity 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Пилюля поиска: всегда в правом углу хедера */
|
||||||
|
.search-pill {
|
||||||
|
position: absolute;
|
||||||
|
right: 12px;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 28px;
|
||||||
|
width: 28px; /* свёрнута — круглая кнопка */
|
||||||
|
border-radius: 9999px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
background:
|
||||||
|
linear-gradient(160deg, rgba(255,255,255,0.11) 0%, rgba(255,255,255,0.04) 100%),
|
||||||
|
rgba(18, 18, 28, 0.60);
|
||||||
|
backdrop-filter: blur(32px) saturate(2);
|
||||||
|
-webkit-backdrop-filter: blur(32px) saturate(2);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.13);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.16),
|
||||||
|
0 2px 12px rgba(0, 0, 0, 0.35);
|
||||||
|
|
||||||
|
/* clip-path даёт pill-форму при clip без overflow:hidden */
|
||||||
|
clip-path: inset(0 round 9999px);
|
||||||
|
|
||||||
|
transition:
|
||||||
|
width 0.30s cubic-bezier(0.34, 1.12, 0.64, 1),
|
||||||
|
background 0.2s ease,
|
||||||
|
border-color 0.2s ease,
|
||||||
|
box-shadow 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill:hover:not(.search-pill--open) {
|
||||||
|
background:
|
||||||
|
linear-gradient(160deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.07) 100%),
|
||||||
|
rgba(18, 18, 28, 0.72);
|
||||||
|
border-color: rgba(255, 255, 255, 0.22);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.20),
|
||||||
|
0 3px 16px rgba(0, 0, 0, 0.40);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill--open {
|
||||||
|
width: calc(100% - 24px);
|
||||||
|
cursor: default;
|
||||||
|
background:
|
||||||
|
linear-gradient(160deg, rgba(255,255,255,0.09) 0%, rgba(255,255,255,0.02) 100%),
|
||||||
|
rgba(12, 12, 20, 0.75);
|
||||||
|
border-color: color-mix(in srgb, var(--accent) 45%, rgba(255,255,255,0.14));
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.15),
|
||||||
|
0 0 0 2.5px color-mix(in srgb, var(--accent) 22%, transparent),
|
||||||
|
0 4px 24px rgba(0, 0, 0, 0.40);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: rgba(255, 255, 255, 0.45);
|
||||||
|
transition: color 0.18s ease;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill--open .search-pill-icon {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 13px;
|
||||||
|
caret-color: var(--accent);
|
||||||
|
padding: 0 4px 0 0;
|
||||||
|
/* Скрыт пока pill свёрнута */
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.18s ease 0.08s;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill--open .search-pill-input {
|
||||||
|
opacity: 1;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-input::placeholder {
|
||||||
|
color: rgba(255, 255, 255, 0.28);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-spinner {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-right: 6px;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-close {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 50%;
|
||||||
|
color: rgba(255, 255, 255, 0.35);
|
||||||
|
margin-right: 4px;
|
||||||
|
transition: background 0.15s ease, color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-pill-close:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
color: rgba(255, 255, 255, 0.80);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Search results ──────────────────────────────────────── */
|
||||||
|
.search-results-list {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 4px 0 8px;
|
||||||
|
mask-image: linear-gradient(to bottom, black 0%, black calc(100% - 56px), transparent 100%);
|
||||||
|
-webkit-mask-image: linear-gradient(to bottom, black 0%, black calc(100% - 56px), transparent 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results-count {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
padding: 4px 12px 6px;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-item {
|
||||||
|
margin: 2px 5px;
|
||||||
|
padding: 9px 11px 8px;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background var(--transition-fast), box-shadow var(--transition-fast);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
background: rgba(255, 255, 255, 0.02);
|
||||||
|
border: 1px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-item:hover {
|
||||||
|
background:
|
||||||
|
linear-gradient(135deg, rgba(255, 255, 255, 0.06) 0%, rgba(255, 255, 255, 0.02) 100%),
|
||||||
|
rgba(14, 14, 22, 0.40);
|
||||||
|
border-color: rgba(255, 255, 255, 0.07);
|
||||||
|
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-item.selected {
|
||||||
|
background: var(--bg-selected);
|
||||||
|
border-color: color-mix(in srgb, var(--accent) 25%, transparent);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 color-mix(in srgb, var(--accent) 15%, transparent),
|
||||||
|
0 2px 8px color-mix(in srgb, var(--accent) 10%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 6px;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-from {
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-date {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-subject {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-result-folder {
|
||||||
|
font-size: 10.5px;
|
||||||
|
color: var(--accent);
|
||||||
|
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 22%, transparent);
|
||||||
|
border-radius: var(--radius-full);
|
||||||
|
padding: 1px 7px;
|
||||||
|
align-self: flex-start;
|
||||||
|
line-height: 16px;
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,138 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import NotificationToast from './NotificationToast.vue'
|
||||||
|
import { useIpc } from '../../composables/useIpc'
|
||||||
|
import { useAccountsStore } from '../../stores/accounts.store'
|
||||||
|
import { useFoldersStore } from '../../stores/folders.store'
|
||||||
|
import { useMessagesStore } from '../../stores/messages.store'
|
||||||
|
|
||||||
|
interface ToastItem {
|
||||||
|
id: string
|
||||||
|
from: string
|
||||||
|
subject: string
|
||||||
|
accountEmail: string
|
||||||
|
accountId: string
|
||||||
|
folderId: string
|
||||||
|
messageId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const toasts = ref<ToastItem[]>([])
|
||||||
|
const DURATION = 5000
|
||||||
|
let counter = 0
|
||||||
|
|
||||||
|
const { on } = useIpc()
|
||||||
|
const accountsStore = useAccountsStore()
|
||||||
|
const foldersStore = useFoldersStore()
|
||||||
|
const messagesStore = useMessagesStore()
|
||||||
|
|
||||||
|
function addToast(item: Omit<ToastItem, 'id'>): void {
|
||||||
|
const id = `toast-${++counter}`
|
||||||
|
toasts.value.push({ id, ...item })
|
||||||
|
setTimeout(() => removeToast(id), DURATION)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeToast(id: string): void {
|
||||||
|
const idx = toasts.value.findIndex(t => t.id === id)
|
||||||
|
if (idx !== -1) toasts.value.splice(idx, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClick(id: string): void {
|
||||||
|
const toast = toasts.value.find(t => t.id === id)
|
||||||
|
if (!toast) return
|
||||||
|
accountsStore.setActive(toast.accountId)
|
||||||
|
foldersStore.setActiveFolder(toast.folderId)
|
||||||
|
messagesStore.selectMessage(toast.messageId)
|
||||||
|
removeToast(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function showOsNotification(from: string, subject: string, onClick: () => void): void {
|
||||||
|
if (!('Notification' in window)) return
|
||||||
|
const send = (): void => {
|
||||||
|
const n = new window.Notification(from, { body: subject, silent: false })
|
||||||
|
n.onclick = () => { onClick(); n.close() }
|
||||||
|
}
|
||||||
|
if (Notification.permission === 'granted') {
|
||||||
|
send()
|
||||||
|
} else if (Notification.permission !== 'denied') {
|
||||||
|
Notification.requestPermission().then(p => { if (p === 'granted') send() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Запросить разрешение при старте + слушать события
|
||||||
|
onMounted(() => {
|
||||||
|
if ('Notification' in window && Notification.permission === 'default') {
|
||||||
|
Notification.requestPermission()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Новые письма из любой папки (через pollNewMessages в main)
|
||||||
|
on('mail:new', ({ accountId, folderId, envelope }) => {
|
||||||
|
const account = accountsStore.accounts.find(a => a.id === accountId)
|
||||||
|
if (!account) return
|
||||||
|
const from = envelope.from.name || envelope.from.email
|
||||||
|
const subject = envelope.subject || '(без темы)'
|
||||||
|
addToast({ from, subject, accountEmail: account.email, accountId, folderId, messageId: envelope.id })
|
||||||
|
showOsNotification(from, subject, () => {
|
||||||
|
accountsStore.setActive(accountId)
|
||||||
|
foldersStore.setActiveFolder(folderId)
|
||||||
|
messagesStore.selectMessage(envelope.id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
on('notification:click', ({ accountId, folderId, messageId }) => {
|
||||||
|
accountsStore.setActive(accountId)
|
||||||
|
foldersStore.setActiveFolder(folderId)
|
||||||
|
messagesStore.selectMessage(messageId)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div class="toast-container">
|
||||||
|
<TransitionGroup name="toast" tag="div" class="toast-list">
|
||||||
|
<NotificationToast
|
||||||
|
v-for="toast in toasts"
|
||||||
|
:key="toast.id"
|
||||||
|
v-bind="toast"
|
||||||
|
:on-close="removeToast"
|
||||||
|
:on-click="handleClick"
|
||||||
|
/>
|
||||||
|
</TransitionGroup>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.toast-container {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 20px;
|
||||||
|
right: 20px;
|
||||||
|
z-index: 99999;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-enter-active,
|
||||||
|
.toast-leave-active {
|
||||||
|
transition:
|
||||||
|
opacity 220ms ease,
|
||||||
|
transform 220ms cubic-bezier(0.34, 1.15, 0.64, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-enter-from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(20px) scale(0.96);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(20px) scale(0.96);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
152
src/renderer/src/components/notifications/NotificationToast.vue
Normal file
152
src/renderer/src/components/notifications/NotificationToast.vue
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import AppIcon from '../AppIcon.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
id: string
|
||||||
|
from: string
|
||||||
|
subject: string
|
||||||
|
accountEmail: string
|
||||||
|
onClose: (id: string) => void
|
||||||
|
onClick: (id: string) => void
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const visible = ref(false)
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
requestAnimationFrame(() => { visible.value = true })
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="toast"
|
||||||
|
:class="{ visible }"
|
||||||
|
@click="onClick(id)"
|
||||||
|
>
|
||||||
|
<div class="toast-icon">
|
||||||
|
<AppIcon name="envelope" :size="16" />
|
||||||
|
</div>
|
||||||
|
<div class="toast-body">
|
||||||
|
<div class="toast-from">{{ from }}</div>
|
||||||
|
<div class="toast-subject">{{ subject }}</div>
|
||||||
|
<div class="toast-account">{{ accountEmail }}</div>
|
||||||
|
</div>
|
||||||
|
<button class="toast-close" @click.stop="onClose(id)">
|
||||||
|
<svg width="9" height="9" viewBox="0 0 9 9" fill="none">
|
||||||
|
<line x1="1" y1="1" x2="8" y2="8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
||||||
|
<line x1="8" y1="1" x2="1" y2="8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.toast {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
width: 320px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
background:
|
||||||
|
linear-gradient(145deg, rgba(255,255,255,0.12) 0%, rgba(255,255,255,0.05) 100%),
|
||||||
|
rgba(12, 12, 22, 0.88);
|
||||||
|
backdrop-filter: blur(40px) saturate(2.0);
|
||||||
|
-webkit-backdrop-filter: blur(40px) saturate(2.0);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.20),
|
||||||
|
0 8px 32px rgba(0, 0, 0, 0.50),
|
||||||
|
0 2px 8px rgba(0, 0, 0, 0.30);
|
||||||
|
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateX(20px) scale(0.96);
|
||||||
|
transition:
|
||||||
|
opacity 220ms cubic-bezier(0.34, 1.15, 0.64, 1),
|
||||||
|
transform 220ms cubic-bezier(0.34, 1.15, 0.64, 1);
|
||||||
|
pointer-events: all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast.visible {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateX(0) scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast:hover {
|
||||||
|
background:
|
||||||
|
linear-gradient(145deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.08) 100%),
|
||||||
|
rgba(14, 14, 24, 0.92);
|
||||||
|
border-color: rgba(255, 255, 255, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border-radius: 8px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: var(--accent);
|
||||||
|
background: color-mix(in srgb, var(--accent) 14%, transparent);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent);
|
||||||
|
margin-top: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-from {
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-subject {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-account {
|
||||||
|
font-size: 10.5px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-close {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: var(--text-muted);
|
||||||
|
background: rgba(255, 255, 255, 0.06);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.09);
|
||||||
|
margin-top: 1px;
|
||||||
|
transition: background var(--transition-fast), color var(--transition-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast-close:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -28,6 +28,11 @@ export const useAccountsStore = defineStore('accounts', () => {
|
||||||
connected: result.success,
|
connected: result.success,
|
||||||
error: result.error
|
error: result.error
|
||||||
}
|
}
|
||||||
|
// Инициализируем lastUnseenCount сразу после подключения —
|
||||||
|
// иначе первый autoCheckTimer только заполняет карту, а второй уже шлёт уведомления.
|
||||||
|
if (result.success) {
|
||||||
|
invoke('messages:poll', { accountId: acc.id }).catch(() => {})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (accounts.value.length > 0 && !activeAccountId.value) {
|
if (accounts.value.length > 0 && !activeAccountId.value) {
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,30 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
// Unread filter
|
// Unread filter
|
||||||
const unreadOnly = ref(false)
|
const unreadOnly = ref(false)
|
||||||
|
|
||||||
|
// Search
|
||||||
|
const searchQuery = ref('')
|
||||||
|
const searchResults = ref<MessageEnvelope[]>([])
|
||||||
|
const searchLoading = ref(false)
|
||||||
|
const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
|
||||||
|
|
||||||
|
// Отслеживание новых писем между обновлениями
|
||||||
|
const knownIds = new Map<string, Set<string>>() // key = accountId:folderId
|
||||||
|
const newArrivals = ref<Array<{ accountId: string; folderId: string; envelope: MessageEnvelope }>>([])
|
||||||
|
|
||||||
|
function detectNewMessages(accountId: string, folderId: string, fresh: MessageEnvelope[]): void {
|
||||||
|
const key = `${accountId}:${folderId}`
|
||||||
|
const prev = knownIds.get(key)
|
||||||
|
const nextIds = new Set(fresh.map(m => m.id))
|
||||||
|
knownIds.set(key, nextIds)
|
||||||
|
|
||||||
|
if (!prev) return
|
||||||
|
|
||||||
|
const arrived = fresh.filter(m => !prev.has(m.id) && !m.flags.seen)
|
||||||
|
for (const envelope of arrived) {
|
||||||
|
newArrivals.value = [{ accountId, folderId, envelope }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const filteredMessages = computed(() =>
|
const filteredMessages = computed(() =>
|
||||||
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
|
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
|
||||||
)
|
)
|
||||||
|
|
@ -63,6 +87,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
if (offset === 0) {
|
if (offset === 0) {
|
||||||
|
detectNewMessages(accountId, folderId, result.messages)
|
||||||
messages.value = result.messages
|
messages.value = result.messages
|
||||||
if (unreadOnly.value) {
|
if (unreadOnly.value) {
|
||||||
// result.total — это точное число непрочитанных из SEARCH UNSEEN
|
// result.total — это точное число непрочитанных из SEARCH UNSEEN
|
||||||
|
|
@ -310,6 +335,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
(folderId) => {
|
(folderId) => {
|
||||||
clearSelection()
|
clearSelection()
|
||||||
clearSelected()
|
clearSelected()
|
||||||
|
clearSearch()
|
||||||
messages.value = []
|
messages.value = []
|
||||||
totalCount.value = 0
|
totalCount.value = 0
|
||||||
unreadOnly.value = false
|
unreadOnly.value = false
|
||||||
|
|
@ -319,6 +345,34 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async function search(query: string): Promise<void> {
|
||||||
|
searchQuery.value = query
|
||||||
|
if (!query.trim()) {
|
||||||
|
searchResults.value = []
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!accountsStore.activeAccountId) return
|
||||||
|
searchLoading.value = true
|
||||||
|
try {
|
||||||
|
const results = await invoke('messages:search', {
|
||||||
|
accountId: accountsStore.activeAccountId,
|
||||||
|
query: query.trim(),
|
||||||
|
limit: 50
|
||||||
|
})
|
||||||
|
searchResults.value = Array.isArray(results) ? results : []
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[search] invoke error:', e)
|
||||||
|
searchResults.value = []
|
||||||
|
} finally {
|
||||||
|
searchLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSearch(): void {
|
||||||
|
searchQuery.value = ''
|
||||||
|
searchResults.value = []
|
||||||
|
}
|
||||||
|
|
||||||
// Listen for new mail
|
// Listen for new mail
|
||||||
on('mail:new', (data) => {
|
on('mail:new', (data) => {
|
||||||
if (
|
if (
|
||||||
|
|
@ -343,6 +397,13 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
messageBody,
|
messageBody,
|
||||||
loading,
|
loading,
|
||||||
loadingBody,
|
loadingBody,
|
||||||
|
newArrivals,
|
||||||
|
searchQuery,
|
||||||
|
searchResults,
|
||||||
|
searchLoading,
|
||||||
|
isSearchActive,
|
||||||
|
search,
|
||||||
|
clearSearch,
|
||||||
loadMessages,
|
loadMessages,
|
||||||
loadMore,
|
loadMore,
|
||||||
selectMessage,
|
selectMessage,
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,8 @@ export interface IpcChannelMap {
|
||||||
|
|
||||||
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
|
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
|
||||||
|
|
||||||
|
'messages:poll': [{ accountId: string }, void]
|
||||||
|
'messages:search': [{ accountId: string; query: string; limit: number }, MessageEnvelope[]]
|
||||||
'app:setZoom': [{ factor: number }, void]
|
'app:setZoom': [{ factor: number }, void]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -45,6 +47,7 @@ export interface IpcEventMap {
|
||||||
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope }
|
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope }
|
||||||
'account:status': { accountId: string; connected: boolean; error?: string }
|
'account:status': { accountId: string; connected: boolean; error?: string }
|
||||||
'attachment:progress': { attachmentId: string; stage: 'downloading' | 'saving' | 'done' | 'error'; progress: number; error?: string }
|
'attachment:progress': { attachmentId: string; stage: 'downloading' | 'saving' | 'done' | 'error'; progress: number; error?: string }
|
||||||
|
'notification:click': { accountId: string; folderId: string; messageId: string }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IpcChannel = keyof IpcChannelMap
|
export type IpcChannel = keyof IpcChannelMap
|
||||||
|
|
|
||||||
|
|
@ -30,4 +30,6 @@ export interface IEmailProvider {
|
||||||
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
|
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
|
||||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
|
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
|
||||||
offNewMail(): void
|
offNewMail(): void
|
||||||
|
pollNewMessages(): Promise<void>
|
||||||
|
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue