fix/search: переподключение при NoConnection + корректный отображение капсулы поиска

- imap.provider: убран try/catch вокруг listTree() — ошибки соединения
  теперь долетают до withAutoReconnect и триггерят переподключение
- imap.provider: Array.isArray() для результатов search() — защита от
  неожиданного типа ответа сервера
- MessageList: search-pill-icon перенесён на <span> вместо прямого
  применения к <svg> (display:flex на SVG не работает, иконка тянулась)
- MessageList: v-model + watch вместо :value/@input для инпута поиска
- messages.store: catch + Array.isArray для результатов invoke

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
d.a.kolesov 2026-04-06 13:58:44 +07:00
parent 025ffccbe0
commit 3b3da5b0fb
3 changed files with 41 additions and 24 deletions

View file

@ -278,10 +278,10 @@ export class ImapProvider implements IEmailProvider {
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> { async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
const results: MessageEnvelope[] = [] const results: MessageEnvelope[] = []
try { // Не ловим ошибки здесь — они должны попасть в withAutoReconnect (AccountManager)
const tree = await this.client.listTree() as { folders?: ImapMailbox[] } // для переподключения при NoConnection и прочих сетевых сбоях
await this.searchFolderTree(tree.folders ?? [], query, limit, results) const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
} catch { /* ignore */ } await this.searchFolderTree(tree.folders ?? [], query, limit, results)
return results return results
} }
@ -313,13 +313,14 @@ export class ImapProvider implements IEmailProvider {
try { try {
lock = await this.client.getMailboxLock(folder.path) lock = await this.client.getMailboxLock(folder.path)
// SUBJECT — быстрый поиск по теме (серверный индекс, не требует загрузки тел) // SUBJECT + FROM — серверный поиск (быстрее, чем TEXT по телу)
const subjectUids = await this.client.search({ subject: query }, { uid: true }) as number[] const rawSubject = await this.client.search({ subject: query }, { uid: true })
// FROM — дополнительный поиск по отправителю const rawFrom = await this.client.search({ from: query }, { uid: true })
const fromUids = await this.client.search({ from: query }, { uid: true }) as number[] const subjectUids = Array.isArray(rawSubject) ? rawSubject : []
const fromUids = Array.isArray(rawFrom) ? rawFrom : []
// Объединяем UIDs без дублей // Объединяем UIDs без дублей
const merged = [...new Set([...(subjectUids ?? []), ...(fromUids ?? [])])] const merged = [...new Set([...subjectUids, ...fromUids])]
if (merged.length) { if (merged.length) {
const remaining = limit - results.length const remaining = limit - results.length
@ -330,7 +331,9 @@ export class ImapProvider implements IEmailProvider {
results.push(this.convertMessage(msg, folder.path)) results.push(this.convertMessage(msg, folder.path))
} }
} }
} catch { /* папка не поддерживает SEARCH или временно недоступна */ } } catch (e) {
console.error('[IMAP:search] folder error:', folder?.path, e)
}
finally { finally {
lock?.release() lock?.release()
} }

View file

@ -20,13 +20,26 @@ const { invoke } = useIpc()
const selectMode = ref(false) const selectMode = ref(false)
// ── Search ──────────────────────────────────────────────── // ── Search ────────────────────────────────────────────────
const searchOpen = ref(false) const searchOpen = ref(false)
const searchInputEl = ref<HTMLInputElement | null>(null) const searchInputEl = ref<HTMLInputElement | null>(null)
const localSearchQuery = ref('')
let searchDebounce: ReturnType<typeof setTimeout> | null = null 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 { function openSearch(): void {
searchOpen.value = true searchOpen.value = true
// Фокус после того как анимация начнётся (иначе браузер скроллит до элемента)
setTimeout(() => { setTimeout(() => {
searchInputEl.value?.removeAttribute('tabindex') searchInputEl.value?.removeAttribute('tabindex')
searchInputEl.value?.focus() searchInputEl.value?.focus()
@ -35,16 +48,11 @@ function openSearch(): void {
function closeSearch(): void { function closeSearch(): void {
searchOpen.value = false searchOpen.value = false
localSearchQuery.value = ''
searchInputEl.value?.setAttribute('tabindex', '-1') searchInputEl.value?.setAttribute('tabindex', '-1')
messagesStore.clearSearch() 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 { function onSearchKeydown(e: KeyboardEvent): void {
if (e.key === 'Escape') closeSearch() if (e.key === 'Escape') closeSearch()
} }
@ -353,14 +361,15 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
:class="{ 'search-pill--open': searchOpen }" :class="{ 'search-pill--open': searchOpen }"
@click="!searchOpen && openSearch()" @click="!searchOpen && openSearch()"
> >
<AppIcon name="search" :size="13" class="search-pill-icon" /> <span class="search-pill-icon">
<AppIcon name="search" :size="13" />
</span>
<input <input
ref="searchInputEl" ref="searchInputEl"
class="search-pill-input" class="search-pill-input"
placeholder="Поиск по письмам..." placeholder="Поиск по письмам..."
:value="messagesStore.searchQuery" v-model="localSearchQuery"
tabindex="-1" tabindex="-1"
@input="onSearchInput"
@keydown="onSearchKeydown" @keydown="onSearchKeydown"
/> />
<div v-if="messagesStore.searchLoading" class="spinner-sm search-pill-spinner" /> <div v-if="messagesStore.searchLoading" class="spinner-sm search-pill-spinner" />
@ -1143,7 +1152,8 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
.search-pill-icon { .search-pill-icon {
flex-shrink: 0; flex-shrink: 0;
width: 28px; /* занимает место кнопки — без отступа слева */ width: 28px;
height: 28px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@ -1165,7 +1175,7 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
color: var(--text-primary); color: var(--text-primary);
font-size: 13px; font-size: 13px;
caret-color: var(--accent); caret-color: var(--accent);
padding: 0; padding: 0 4px 0 0;
/* Скрыт пока pill свёрнута */ /* Скрыт пока pill свёрнута */
opacity: 0; opacity: 0;
transition: opacity 0.18s ease 0.08s; transition: opacity 0.18s ease 0.08s;

View file

@ -354,11 +354,15 @@ export const useMessagesStore = defineStore('messages', () => {
if (!accountsStore.activeAccountId) return if (!accountsStore.activeAccountId) return
searchLoading.value = true searchLoading.value = true
try { try {
searchResults.value = await invoke('messages:search', { const results = await invoke('messages:search', {
accountId: accountsStore.activeAccountId, accountId: accountsStore.activeAccountId,
query: query.trim(), query: query.trim(),
limit: 50 limit: 50
}) })
searchResults.value = Array.isArray(results) ? results : []
} catch (e) {
console.error('[search] invoke error:', e)
searchResults.value = []
} finally { } finally {
searchLoading.value = false searchLoading.value = false
} }