feature/search: поиск писем по всем папкам аккаунта

- IPC-канал messages:search + тип в IpcChannelMap
- IMAP: server-side SEARCH OR SUBJECT FROM по всем папкам
- Gmail: search через API q-параметр
- Exchange: stub (пустой результат)
- messages.store: состояние searchQuery/searchResults/searchLoading + actions search/clearSearch
- Сброс поиска при смене папки
- MessageList: поисковая строка в хедере (Ctrl+F / кнопка)
- Результаты с бейджем папки, дебаунс 300ms, Escape закрывает
- Иконки search/close в AppIcon

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
d.a.kolesov 2026-04-06 13:20:16 +07:00
parent 2122b169b8
commit ab1c084b91
10 changed files with 369 additions and 25 deletions

View file

@ -37,6 +37,10 @@ export function registerMessageHandlers(manager: AccountManager): void {
await manager.pollNewMessages(accountId)
})
registerHandler('messages:search', async ({ accountId, query, limit }) => {
return manager.searchMessages(accountId, query, limit)
})
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
return manager.fetchMessageBody(accountId, folderId, messageId)
})

View file

@ -188,6 +188,7 @@ 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 {
const n = name.toLowerCase()

View file

@ -176,6 +176,27 @@ 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 {
switch (labelId) {
case 'INBOX': return SpecialFolderRole.Inbox

View file

@ -276,6 +276,52 @@ export class ImapProvider implements IEmailProvider {
this.client.removeAllListeners('exists')
}
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
const results: MessageEnvelope[] = []
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.searchFolderTree(tree.folders ?? [], query, limit, results)
} catch { /* ignore */ }
return results
}
private async searchFolderTree(
folders: ImapMailbox[],
query: string,
limit: number,
results: MessageEnvelope[]
): Promise<void> {
for (const folder of folders) {
if (results.length >= limit) break
try {
const lock = await this.client.getMailboxLock(folder.path)
try {
// OR SUBJECT FROM — быстрый поиск по заголовкам без загрузки тел
const uids = await this.client.search(
{ or: [{ subject: query }, { from: query }] },
{ uid: true }
) as number[]
if (uids?.length) {
const remaining = limit - results.length
const sorted = [...uids].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))
}
}
} finally {
lock.release()
}
} catch { /* папка не поддерживает SEARCH или временно недоступна */ }
if (folder.folders?.length && results.length < limit) {
await this.searchFolderTree(folder.folders, query, limit, results)
}
}
}
async pollNewMessages(): Promise<void> {
if (!this.newMailCallback) return
try {

View file

@ -127,6 +127,12 @@ export class AccountManager {
if (provider) await provider.pollNewMessages()
}
async searchMessages(accountId: string, query: string, limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> {
const provider = this.providers.get(accountId)
if (!provider) return []
return provider.searchMessages(query, limit)
}
async listMessages(
accountId: string,
folderId: string,

View file

@ -15,6 +15,8 @@ export type IconName =
| 'envelope'
| 'refresh'
| 'threads'
| 'search'
| 'close'
const props = defineProps<{
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="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>

View file

@ -1,5 +1,5 @@
<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 { useFoldersStore } from '../../stores/folders.store'
import { useAccountsStore } from '../../stores/accounts.store'
@ -9,6 +9,7 @@ import MessageListItem from './MessageListItem.vue'
import ThreadListItem from './ThreadListItem.vue'
import AppIcon from '../AppIcon.vue'
import { buildThreads, type Thread } from '../../utils/threading'
import type { MessageEnvelope } from '@shared/types/message'
const messagesStore = useMessagesStore()
const foldersStore = useFoldersStore()
@ -18,6 +19,62 @@ const { invoke } = useIpc()
const selectMode = ref(false)
// ── Search ────────────────────────────────────────────────
const searchOpen = ref(false)
const searchInputEl = ref<HTMLInputElement | null>(null)
let searchDebounce: ReturnType<typeof setTimeout> | null = null
function openSearch(): void {
searchOpen.value = true
nextTick(() => searchInputEl.value?.focus())
}
function closeSearch(): void {
searchOpen.value = false
messagesStore.clearSearch()
}
function onSearchInput(e: Event): void {
const val = (e.target as HTMLInputElement).value
if (searchDebounce) clearTimeout(searchDebounce)
searchDebounce = setTimeout(() => messagesStore.search(val), 300)
}
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 hasSelected = computed(() => messagesStore.selectedIds.size > 0)
const activeUnread = computed(() => {
@ -256,31 +313,54 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
<template>
<div class="message-list-container">
<!-- Заголовок -->
<div class="message-list-header">
<h2 class="folder-title truncate">{{ folderName }}</h2>
<button
v-if="activeUnread > 0 || messagesStore.unreadOnly"
class="message-count"
:class="{ 'unread-active': messagesStore.unreadOnly }"
v-tooltip="'Только непрочитанные'"
@click="messagesStore.toggleUnreadOnly()"
>
{{ activeUnread }}
</button>
<div class="header-actions">
<div class="message-list-header" :class="{ 'search-mode': searchOpen }">
<template v-if="!searchOpen">
<h2 class="folder-title truncate">{{ folderName }}</h2>
<button
class="icon-btn select-mode-btn"
:class="{ active: selectMode }"
v-tooltip="'Режим выбора'"
@click="selectMode = !selectMode"
v-if="activeUnread > 0 || messagesStore.unreadOnly"
class="message-count"
:class="{ 'unread-active': messagesStore.unreadOnly }"
v-tooltip="'Только непрочитанные'"
@click="messagesStore.toggleUnreadOnly()"
>
<span class="select-icon" :class="{ checked: selectMode }">
<svg v-if="selectMode" viewBox="0 0 16 16" width="8" height="8" fill="none">
<polyline points="3,8 6.5,12 13,4" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
{{ activeUnread }}
</button>
</div>
<div class="header-actions">
<button class="icon-btn" v-tooltip="'Поиск (Ctrl+F)'" @click="openSearch">
<AppIcon name="search" :size="13" />
</button>
<button
class="icon-btn select-mode-btn"
:class="{ active: selectMode }"
v-tooltip="'Режим выбора'"
@click="selectMode = !selectMode"
>
<span class="select-icon" :class="{ checked: selectMode }">
<svg v-if="selectMode" viewBox="0 0 16 16" width="8" height="8" fill="none">
<polyline points="3,8 6.5,12 13,4" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
</button>
</div>
</template>
<template v-else>
<div class="search-bar">
<AppIcon name="search" :size="13" class="search-bar-icon" />
<input
ref="searchInputEl"
class="search-input"
placeholder="Поиск по письмам..."
:value="messagesStore.searchQuery"
@input="onSearchInput"
@keydown="onSearchKeydown"
/>
<div v-if="messagesStore.searchLoading" class="spinner-sm" />
</div>
<button class="icon-btn" v-tooltip="'Закрыть поиск'" @click="closeSearch">
<AppIcon name="close" :size="12" />
</button>
</template>
</div>
<!-- Pull-to-refresh индикатор (всегда в DOM, высота = 0 в обычном состоянии) -->
@ -305,9 +385,38 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
</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
v-if="messagesStore.loading && messagesStore.messages.length === 0"
v-else-if="messagesStore.loading && messagesStore.messages.length === 0"
class="loading-state"
>
<div class="spinner" />
@ -945,4 +1054,112 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
}
/* Анимация раскрытия управляется JS-хуками через scrollHeight */
/* ── Search bar ──────────────────────────────────────────── */
.message-list-header.search-mode {
gap: 6px;
}
.search-bar {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 6px;
background: rgba(255, 255, 255, 0.07);
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: var(--radius-full);
padding: 0 10px;
height: 28px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06);
}
.search-bar-icon {
color: var(--text-muted);
flex-shrink: 0;
}
.search-input {
flex: 1;
min-width: 0;
background: none;
border: none;
outline: none;
color: var(--text-primary);
font-size: 13px;
caret-color: var(--accent);
}
.search-input::placeholder {
color: var(--text-muted);
}
/* ── Search results ──────────────────────────────────────── */
.search-results-list {
flex: 1;
overflow-y: auto;
padding: 0;
}
.search-results-count {
font-size: 11px;
color: var(--text-muted);
padding: 6px 12px 4px;
letter-spacing: 0.02em;
}
.search-result-item {
padding: 9px 12px 8px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
cursor: pointer;
transition: background var(--transition-fast);
display: flex;
flex-direction: column;
gap: 3px;
}
.search-result-item:hover {
background: rgba(255, 255, 255, 0.04);
}
.search-result-item.selected {
background: var(--bg-selected);
}
.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;
}
</style>

View file

@ -47,6 +47,12 @@ export const useMessagesStore = defineStore('messages', () => {
// Unread filter
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 }>>([])
@ -329,6 +335,7 @@ export const useMessagesStore = defineStore('messages', () => {
(folderId) => {
clearSelection()
clearSelected()
clearSearch()
messages.value = []
totalCount.value = 0
unreadOnly.value = false
@ -338,6 +345,30 @@ 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 {
searchResults.value = await invoke('messages:search', {
accountId: accountsStore.activeAccountId,
query: query.trim(),
limit: 50
})
} finally {
searchLoading.value = false
}
}
function clearSearch(): void {
searchQuery.value = ''
searchResults.value = []
}
// Listen for new mail
on('mail:new', (data) => {
if (
@ -363,6 +394,12 @@ export const useMessagesStore = defineStore('messages', () => {
loading,
loadingBody,
newArrivals,
searchQuery,
searchResults,
searchLoading,
isSearchActive,
search,
clearSearch,
loadMessages,
loadMore,
selectMessage,

View file

@ -38,7 +38,8 @@ export interface IpcChannelMap {
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
'messages:poll': [{ accountId: string }, void]
'messages:poll': [{ accountId: string }, void]
'messages:search': [{ accountId: string; query: string; limit: number }, MessageEnvelope[]]
'app:setZoom': [{ factor: number }, void]
}

View file

@ -31,4 +31,5 @@ export interface IEmailProvider {
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
offNewMail(): void
pollNewMessages(): Promise<void>
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
}