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)
})
registerHandler('messages:markAllRead', async ({ accountId, folderId }) => {
registerHandler('messages:markAllRead', async ({ accountId, folderIds }) => {
assertId(accountId, 'accountId')
assertId(folderId, 'folderId')
await manager.markAllRead(accountId, folderId)
assertIds(folderIds, 'folderIds')
await manager.markAllRead(accountId, folderIds)
})
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> {
return this.withAutoReconnect(accountId, () =>
this.getProvider(accountId).markAllRead(folderId)
)
async markAllRead(accountId: string, folderIds: string[]): Promise<void> {
return this.withAutoReconnect(accountId, async () => {
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[] {

View file

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

View file

@ -1,10 +1,20 @@
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { useFoldersStore } from '../../stores/folders.store'
import { useAccountsStore } from '../../stores/accounts.store'
import FolderTreeItem from './FolderTreeItem.vue'
const foldersStore = useFoldersStore()
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>
<template>

View file

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

View file

@ -17,6 +17,13 @@ export const useFoldersStore = defineStore('folders', () => {
// Хранится отдельно от дерева — гарантированно реактивен
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(() => {
if (!accountsStore.activeAccountId) return []
return foldersByAccount.value[accountsStore.activeAccountId] ?? []
@ -49,6 +56,64 @@ export const useFoldersStore = defineStore('folders', () => {
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 {
for (const f of folders) {
unreadCounts.value[`${accountId}:${f.id}`] = f.unreadCount
@ -81,6 +146,7 @@ export const useFoldersStore = defineStore('folders', () => {
watch(
() => accountsStore.activeAccountId,
(accountId) => {
clearSelection()
if (accountId) {
if (!foldersByAccount.value[accountId]) {
loadFolders(accountId)
@ -104,10 +170,17 @@ export const useFoldersStore = defineStore('folders', () => {
unreadCounts,
activeFolderId,
activeFolder,
selectedFolderIds,
collapsedFolderIds,
loading,
loadFolders,
refreshUnreadCounts,
setActiveFolder,
isExpanded,
toggleExpanded,
selectFolder,
clearSelection,
collectFolderIds,
updateFolderUnread,
setFolderUnread,
getFolderUnread
@ -137,3 +210,13 @@ function findFolderByRole(folders: Folder[], role: SpecialFolderRole): Folder |
}
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,14 +278,21 @@ export const useMessagesStore = defineStore('messages', () => {
)
}
async function markAllRead(accountId: string, folderId: string): Promise<void> {
await invoke('messages:markAllRead', { accountId, folderId })
if (accountsStore.activeAccountId === accountId && foldersStore.activeFolderId === folderId) {
async function markAllRead(accountId: string, folderIds: string[]): Promise<void> {
if (folderIds.length === 0) return
await invoke('messages:markAllRead', { accountId, folderIds })
if (
accountsStore.activeAccountId === accountId &&
foldersStore.activeFolderId &&
folderIds.includes(foldersStore.activeFolderId)
) {
for (const msg of messages.value) {
msg.flags.seen = true
}
}
foldersStore.setFolderUnread(accountId, folderId, 0)
for (const folderId of folderIds) {
foldersStore.setFolderUnread(accountId, folderId, 0)
}
}
async function toggleFlag(messageId: string): Promise<void> {

View file

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