recursive mark as read
All checks were successful
Release / release (push) Successful in 3m18s

This commit is contained in:
d.a.kolesov 2026-11-11 13:14:58 +07:00
parent df3b48dfbc
commit 137426ed1c
8 changed files with 188 additions and 26 deletions

View file

@ -88,10 +88,10 @@ export function registerMessageHandlers(manager: AccountManager): void {
await manager.deleteMessages(accountId, folderId, messageIds) await manager.deleteMessages(accountId, folderId, messageIds)
}) })
registerHandler('messages:markAllRead', async ({ accountId, folderId }) => { registerHandler('messages:markAllRead', async ({ accountId, folderIds }) => {
assertId(accountId, 'accountId') assertId(accountId, 'accountId')
assertId(folderId, 'folderId') assertIds(folderIds, 'folderIds')
await manager.markAllRead(accountId, folderId) await manager.markAllRead(accountId, folderIds)
}) })
registerHandler('messages:attachment:download', async ({ accountId, folderId, messageId, attachmentId, filename, downloadFolder }) => { registerHandler('messages:attachment:download', async ({ accountId, folderId, messageId, attachmentId, filename, downloadFolder }) => {

View file

@ -211,10 +211,23 @@ export class AccountManager {
) )
} }
async markAllRead(accountId: string, folderId: string): Promise<void> { async markAllRead(accountId: string, folderIds: string[]): Promise<void> {
return this.withAutoReconnect(accountId, () => return this.withAutoReconnect(accountId, async () => {
this.getProvider(accountId).markAllRead(folderId) const provider = this.getProvider(accountId)
) let lastError: unknown = null
let failed = 0
// Последовательно: одно IMAP-соединение, блокировки мейлбоксов не пересекаются.
// Ошибка одной папки (например, \Noselect-контейнер) не прерывает остальные.
for (const folderId of folderIds) {
try {
await provider.markAllRead(folderId)
} catch (error) {
failed++
lastError = error
}
}
if (failed === folderIds.length) throw lastError
})
} }
getConnectedAccountIds(): string[] { getConnectedAccountIds(): string[] {

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue' import { ref, computed, onMounted, onUnmounted } from 'vue'
const props = defineProps<{ const props = defineProps<{
x: number x: number
@ -9,13 +9,16 @@ const props = defineProps<{
folderName: string folderName: string
isMuted: boolean isMuted: boolean
hasRetentionRule: boolean hasRetentionRule: boolean
hasChildren: boolean
/** Сколько папок выделено (>1 — режим мультивыбора). */
selectionCount: number
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
close: [] close: []
mute: [durationMs: number | null] mute: [durationMs: number | null]
unmute: [] unmute: []
markAllRead: [] markAllRead: [recursive: boolean]
editRetention: [] editRetention: []
removeRetention: [] removeRetention: []
}>() }>()
@ -24,6 +27,7 @@ const menuEl = ref<HTMLElement | null>(null)
const menuX = ref(props.x) const menuX = ref(props.x)
const menuY = ref(props.y) const menuY = ref(props.y)
const showSubmenu = ref(false) const showSubmenu = ref(false)
const isMultiSelect = computed(() => props.selectionCount > 1)
const MUTE_OPTIONS = [ const MUTE_OPTIONS = [
{ label: '30 минут', ms: 30 * 60 * 1000 }, { label: '30 минут', ms: 30 * 60 * 1000 },
@ -41,8 +45,8 @@ function handleUnmute(): void {
emit('unmute') emit('unmute')
} }
function handleMarkAllRead(): void { function handleMarkAllRead(recursive: boolean): void {
emit('markAllRead') emit('markAllRead', recursive)
} }
function handleEditRetention(): void { function handleEditRetention(): void {
@ -86,10 +90,24 @@ onUnmounted(() => {
class="context-menu" class="context-menu"
:style="{ left: menuX + 'px', top: menuY + 'px' }" :style="{ left: menuX + 'px', top: menuY + 'px' }"
> >
<button class="menu-item" @click="handleMarkAllRead"> <template v-if="isMultiSelect">
Отметить всё как прочитанное <button class="menu-item" @click="handleMarkAllRead(false)">
Отметить выбранные ({{ selectionCount }}) как прочитанные
</button> </button>
<button v-if="hasChildren" class="menu-item" @click="handleMarkAllRead(true)">
Отметить выбранные ({{ selectionCount }}) с подпапками
</button>
</template>
<template v-else>
<button class="menu-item" @click="handleMarkAllRead(false)">
Отметить как прочитанное
</button>
<button v-if="hasChildren" class="menu-item" @click="handleMarkAllRead(true)">
Отметить как прочитанное (с подпапками)
</button>
</template>
<template v-if="!isMultiSelect">
<div class="menu-divider" /> <div class="menu-divider" />
<!-- Unmute if already muted --> <!-- Unmute if already muted -->
@ -131,6 +149,7 @@ onUnmounted(() => {
<button v-if="hasRetentionRule" class="menu-item" @click="handleRemoveRetention"> <button v-if="hasRetentionRule" class="menu-item" @click="handleRemoveRetention">
Убрать ограничение Убрать ограничение
</button> </button>
</template>
</div> </div>
</Teleport> </Teleport>
</template> </template>

View file

@ -1,10 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
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 FolderTreeItem from './FolderTreeItem.vue' import FolderTreeItem from './FolderTreeItem.vue'
const foldersStore = useFoldersStore() const foldersStore = useFoldersStore()
const accountsStore = useAccountsStore() const accountsStore = useAccountsStore()
function onKeyDown(event: KeyboardEvent): void {
if (event.key === 'Escape' && foldersStore.selectedFolderIds.size > 0) {
foldersStore.clearSelection()
}
}
onMounted(() => document.addEventListener('keydown', onKeyDown))
onUnmounted(() => document.removeEventListener('keydown', onKeyDown))
</script> </script>
<template> <template>

View file

@ -22,11 +22,20 @@ const accountsStore = useAccountsStore()
const notificationsStore = useNotificationsStore() const notificationsStore = useNotificationsStore()
const messagesStore = useMessagesStore() const messagesStore = useMessagesStore()
const retentionStore = useRetentionStore() const retentionStore = useRetentionStore()
const expanded = ref(true)
const contextMenu = ref<{ x: number; y: number } | null>(null) const contextMenu = ref<{ x: number; y: number } | null>(null)
const showRetentionDialog = ref(false) const showRetentionDialog = ref(false)
const expanded = computed(() => foldersStore.isExpanded(props.folder.id))
const isActive = computed(() => foldersStore.activeFolderId === props.folder.id) const isActive = computed(() => foldersStore.activeFolderId === props.folder.id)
const isSelected = computed(() => foldersStore.selectedFolderIds.has(props.folder.id))
// Мультивыбор: меню работает по всем выделенным папкам, если кликнутая среди них
const isMultiSelect = computed(() => isSelected.value && foldersStore.selectedFolderIds.size > 1)
const selectionCount = computed(() => (isMultiSelect.value ? foldersStore.selectedFolderIds.size : 1))
const menuHasChildren = computed(() => {
if (!isMultiSelect.value) return hasChildren.value
return foldersStore.collectFolderIds(foldersStore.selectedFolderIds, true).length >
foldersStore.collectFolderIds(foldersStore.selectedFolderIds, false).length
})
const hasChildren = computed(() => props.folder.children.length > 0) const hasChildren = computed(() => props.folder.children.length > 0)
const unreadCount = computed(() => { const unreadCount = computed(() => {
if (!accountsStore.activeAccountId) return 0 if (!accountsStore.activeAccountId) return 0
@ -53,17 +62,22 @@ const folderIcon = computed((): IconName => {
} }
}) })
function handleClick(): void { function handleClick(event: MouseEvent): void {
foldersStore.setActiveFolder(props.folder.id) foldersStore.selectFolder(props.folder.id, {
shift: event.shiftKey,
ctrl: event.ctrlKey || event.metaKey
})
} }
function toggleExpand(event: Event): void { function toggleExpand(event: Event): void {
event.stopPropagation() event.stopPropagation()
expanded.value = !expanded.value foldersStore.toggleExpanded(props.folder.id)
} }
function handleContextMenu(event: MouseEvent): void { function handleContextMenu(event: MouseEvent): void {
event.preventDefault() event.preventDefault()
// ПКМ вне выделения сбрасывает его: меню относится к кликнутой папке
if (!isSelected.value) foldersStore.clearSelection()
contextMenu.value = { x: event.clientX, y: event.clientY } contextMenu.value = { x: event.clientX, y: event.clientY }
} }
@ -85,9 +99,11 @@ function handleUnmute(): void {
contextMenu.value = null contextMenu.value = null
} }
function handleMarkAllRead(): void { function handleMarkAllRead(recursive: boolean): void {
if (accountsStore.activeAccountId) { if (accountsStore.activeAccountId) {
messagesStore.markAllRead(accountsStore.activeAccountId, props.folder.id) const sourceIds = isMultiSelect.value ? [...foldersStore.selectedFolderIds] : [props.folder.id]
const folderIds = foldersStore.collectFolderIds(sourceIds, recursive)
messagesStore.markAllRead(accountsStore.activeAccountId, folderIds)
} }
contextMenu.value = null contextMenu.value = null
} }
@ -116,7 +132,7 @@ function handleSaveRetention(maxMessages: number, recursive: boolean): void {
<div class="folder-item-wrapper"> <div class="folder-item-wrapper">
<button <button
class="folder-item" class="folder-item"
:class="{ active: isActive }" :class="{ active: isActive, selected: isSelected }"
:style="{ paddingLeft: (depth * 16 + 8) + 'px' }" :style="{ paddingLeft: (depth * 16 + 8) + 'px' }"
@click="handleClick" @click="handleClick"
@contextmenu.prevent="handleContextMenu" @contextmenu.prevent="handleContextMenu"
@ -148,6 +164,8 @@ function handleSaveRetention(maxMessages: number, recursive: boolean): void {
:folder-name="folder.name" :folder-name="folder.name"
:is-muted="isMuted" :is-muted="isMuted"
:has-retention-rule="!!ownRetentionRule" :has-retention-rule="!!ownRetentionRule"
:has-children="menuHasChildren"
:selection-count="selectionCount"
@close="closeContextMenu" @close="closeContextMenu"
@mute="handleMute" @mute="handleMute"
@unmute="handleUnmute" @unmute="handleUnmute"
@ -202,6 +220,13 @@ function handleSaveRetention(maxMessages: number, recursive: boolean): void {
0 2px 8px rgba(0, 0, 0, 0.20); 0 2px 8px rgba(0, 0, 0, 0.20);
} }
/* ── Мультивыбор (Shift/Ctrl+клик) ───────────────────────── */
.folder-item.selected {
background: rgba(255, 255, 255, 0.10);
border-color: rgba(255, 255, 255, 0.22);
user-select: none;
}
/* ── Активное состояние: liquid glass ────────────────────── */ /* ── Активное состояние: liquid glass ────────────────────── */
.folder-item.active { .folder-item.active {
background: linear-gradient( background: linear-gradient(
@ -345,6 +370,11 @@ html[data-design='material3'] .folder-item:hover {
box-shadow: none; box-shadow: none;
} }
html[data-design='material3'] .folder-item.selected {
background: var(--md-sys-color-secondary-container);
border-color: transparent;
}
html[data-design='material3'] .folder-item.active { html[data-design='material3'] .folder-item.active {
background: var(--md-sys-color-secondary-container); background: var(--md-sys-color-secondary-container);
backdrop-filter: none; backdrop-filter: none;

View file

@ -17,6 +17,13 @@ export const useFoldersStore = defineStore('folders', () => {
// Хранится отдельно от дерева — гарантированно реактивен // Хранится отдельно от дерева — гарантированно реактивен
const unreadCounts = ref<Record<string, number>>({}) const unreadCounts = ref<Record<string, number>>({})
// Свёрнутые папки (общее для всех аккаунтов: id папок уникальны в пределах аккаунта,
// коллизия между аккаунтами лишь синхронно сворачивает одноимённые папки)
const collapsedFolderIds = ref<Set<string>>(new Set())
// Мультивыбор папок (Shift/Ctrl+клик)
const selectedFolderIds = ref<Set<string>>(new Set())
const selectionAnchorId = ref<string | null>(null)
const folders = computed(() => { const folders = computed(() => {
if (!accountsStore.activeAccountId) return [] if (!accountsStore.activeAccountId) return []
return foldersByAccount.value[accountsStore.activeAccountId] ?? [] return foldersByAccount.value[accountsStore.activeAccountId] ?? []
@ -49,6 +56,64 @@ export const useFoldersStore = defineStore('folders', () => {
activeFolderId.value = folderId activeFolderId.value = folderId
} }
function isExpanded(folderId: string): boolean {
return !collapsedFolderIds.value.has(folderId)
}
function toggleExpanded(folderId: string): void {
const next = new Set(collapsedFolderIds.value)
if (!next.delete(folderId)) next.add(folderId)
collapsedFolderIds.value = next
}
function clearSelection(): void {
selectedFolderIds.value = new Set()
selectionAnchorId.value = null
}
/** Клик по папке: без модификаторов — обычная активация, Shift — диапазон, Ctrl/Cmd — переключение. */
function selectFolder(
folderId: string,
modifiers: { shift?: boolean; ctrl?: boolean } = {}
): void {
if (modifiers.shift && selectionAnchorId.value) {
const order = flattenVisible(folders.value, collapsedFolderIds.value)
const from = order.indexOf(selectionAnchorId.value)
const to = order.indexOf(folderId)
if (from !== -1 && to !== -1) {
const [start, end] = from <= to ? [from, to] : [to, from]
selectedFolderIds.value = new Set(order.slice(start, end + 1))
return
}
}
if (modifiers.ctrl) {
const next = new Set(selectedFolderIds.value)
// Первый Ctrl+клик включает в выделение и активную папку
if (next.size === 0 && activeFolderId.value) next.add(activeFolderId.value)
if (!next.delete(folderId)) next.add(folderId)
selectedFolderIds.value = next
selectionAnchorId.value = folderId
return
}
clearSelection()
selectionAnchorId.value = folderId
activeFolderId.value = folderId
}
/** Возвращает id папок и (при recursive) всех их потомков без дублей. */
function collectFolderIds(ids: Iterable<string>, recursive: boolean): string[] {
const result = new Set<string>()
const add = (folder: Folder): void => {
result.add(folder.id)
if (recursive) folder.children.forEach(add)
}
for (const id of ids) {
const folder = findFolderById(folders.value, id)
if (folder) add(folder)
}
return [...result]
}
function initUnreadCounts(accountId: string, folders: Folder[]): void { function initUnreadCounts(accountId: string, folders: Folder[]): void {
for (const f of folders) { for (const f of folders) {
unreadCounts.value[`${accountId}:${f.id}`] = f.unreadCount unreadCounts.value[`${accountId}:${f.id}`] = f.unreadCount
@ -81,6 +146,7 @@ export const useFoldersStore = defineStore('folders', () => {
watch( watch(
() => accountsStore.activeAccountId, () => accountsStore.activeAccountId,
(accountId) => { (accountId) => {
clearSelection()
if (accountId) { if (accountId) {
if (!foldersByAccount.value[accountId]) { if (!foldersByAccount.value[accountId]) {
loadFolders(accountId) loadFolders(accountId)
@ -104,10 +170,17 @@ export const useFoldersStore = defineStore('folders', () => {
unreadCounts, unreadCounts,
activeFolderId, activeFolderId,
activeFolder, activeFolder,
selectedFolderIds,
collapsedFolderIds,
loading, loading,
loadFolders, loadFolders,
refreshUnreadCounts, refreshUnreadCounts,
setActiveFolder, setActiveFolder,
isExpanded,
toggleExpanded,
selectFolder,
clearSelection,
collectFolderIds,
updateFolderUnread, updateFolderUnread,
setFolderUnread, setFolderUnread,
getFolderUnread getFolderUnread
@ -137,3 +210,13 @@ function findFolderByRole(folders: Folder[], role: SpecialFolderRole): Folder |
} }
return null return null
} }
/** Плоский pre-order список id видимых папок (потомки свёрнутых пропускаются). */
function flattenVisible(folders: Folder[], collapsed: Set<string>): string[] {
const result: string[] = []
for (const f of folders) {
result.push(f.id)
if (!collapsed.has(f.id)) result.push(...flattenVisible(f.children, collapsed))
}
return result
}

View file

@ -278,15 +278,22 @@ export const useMessagesStore = defineStore('messages', () => {
) )
} }
async function markAllRead(accountId: string, folderId: string): Promise<void> { async function markAllRead(accountId: string, folderIds: string[]): Promise<void> {
await invoke('messages:markAllRead', { accountId, folderId }) if (folderIds.length === 0) return
if (accountsStore.activeAccountId === accountId && foldersStore.activeFolderId === folderId) { await invoke('messages:markAllRead', { accountId, folderIds })
if (
accountsStore.activeAccountId === accountId &&
foldersStore.activeFolderId &&
folderIds.includes(foldersStore.activeFolderId)
) {
for (const msg of messages.value) { for (const msg of messages.value) {
msg.flags.seen = true msg.flags.seen = true
} }
} }
for (const folderId of folderIds) {
foldersStore.setFolderUnread(accountId, folderId, 0) foldersStore.setFolderUnread(accountId, folderId, 0)
} }
}
async function toggleFlag(messageId: string): Promise<void> { async function toggleFlag(messageId: string): Promise<void> {
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return

View file

@ -31,7 +31,7 @@ export interface IpcChannelMap {
void void
] ]
'messages:markAllRead': [ 'messages:markAllRead': [
{ accountId: string; folderId: string }, { accountId: string; folderIds: string[] },
void void
] ]
'messages:attachment:download': [ 'messages:attachment:download': [