Initial commit: Vue Mail Electron client
- IMAP-only email client with Electron + Vue 3 + Pinia - Native GTK titlebar, no default Electron menu - Resizable sidebar panels via drag handles - Message list with swipe gestures (left/right) for delete/read/flag - Multi-select mode with bulk delete, mark-as-read, flag actions - Unread-only filter toggle on message count badge - Message body cache with 3-hour TTL - Custom circular checkboxes for selection UI - Swipe action configuration in settings - Russian UI Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
cd5f236076
56 changed files with 14018 additions and 0 deletions
2
.env.example
Normal file
2
.env.example
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
GMAIL_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
||||
GMAIL_CLIENT_SECRET=your-client-secret
|
||||
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
node_modules/
|
||||
out/
|
||||
dist/
|
||||
*.log
|
||||
.DS_Store
|
||||
23
electron-builder.yml
Normal file
23
electron-builder.yml
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
appId: com.vuemail.app
|
||||
productName: Vue Mail
|
||||
directories:
|
||||
buildResources: resources
|
||||
output: dist
|
||||
files:
|
||||
- out/**/*
|
||||
- "!node_modules/**/*"
|
||||
linux:
|
||||
target:
|
||||
- AppImage
|
||||
- deb
|
||||
category: Network
|
||||
icon: resources/icon.png
|
||||
win:
|
||||
target:
|
||||
- nsis
|
||||
icon: resources/icon.png
|
||||
mac:
|
||||
target:
|
||||
- dmg
|
||||
icon: resources/icon.png
|
||||
category: public.app-category.productivity
|
||||
39
electron.vite.config.ts
Normal file
39
electron.vite.config.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { resolve } from 'path'
|
||||
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { config as dotenv } from 'dotenv'
|
||||
|
||||
dotenv()
|
||||
|
||||
export default defineConfig({
|
||||
main: {
|
||||
plugins: [externalizeDepsPlugin()],
|
||||
define: {
|
||||
'process.env.GMAIL_CLIENT_ID': JSON.stringify(process.env.GMAIL_CLIENT_ID ?? ''),
|
||||
'process.env.GMAIL_CLIENT_SECRET': JSON.stringify(process.env.GMAIL_CLIENT_SECRET ?? '')
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@shared': resolve('src/shared'),
|
||||
'@main': resolve('src/main')
|
||||
}
|
||||
}
|
||||
},
|
||||
preload: {
|
||||
plugins: [externalizeDepsPlugin()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@shared': resolve('src/shared')
|
||||
}
|
||||
}
|
||||
},
|
||||
renderer: {
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@shared': resolve('src/shared'),
|
||||
'@renderer': resolve('src/renderer/src')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
9266
package-lock.json
generated
Normal file
9266
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
47
package.json
Normal file
47
package.json
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
{
|
||||
"name": "vue-mail",
|
||||
"version": "0.1.0",
|
||||
"description": "Desktop email client built with Vue 3 + Electron",
|
||||
"main": "./out/main/index.js",
|
||||
"scripts": {
|
||||
"dev": "electron-vite dev",
|
||||
"build": "electron-vite build",
|
||||
"preview": "electron-vite preview",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"build:unpack": "npm run build && electron-builder --dir",
|
||||
"build:linux": "npm run build && electron-builder --linux",
|
||||
"build:win": "npm run build && electron-builder --win",
|
||||
"build:mac": "npm run build && electron-builder --mac",
|
||||
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
|
||||
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/vue-virtual": "^3.13.6",
|
||||
"@types/mailparser": "^3.4.6",
|
||||
"@types/sanitize-html": "^2.16.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.2.4",
|
||||
"dotenv": "^17.3.1",
|
||||
"electron-store": "^8.2.0",
|
||||
"ews-javascript-api": "^0.11.0",
|
||||
"googleapis": "^144.0.0",
|
||||
"imapflow": "^1.0.171",
|
||||
"jsdom": "^29.0.1",
|
||||
"mailparser": "^3.9.6",
|
||||
"pinia": "^3.0.2",
|
||||
"sanitize-html": "^2.17.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/dompurify": "^3.2.0",
|
||||
"@vitejs/plugin-vue": "^5.2.3",
|
||||
"electron": "^35.1.2",
|
||||
"electron-builder": "^25.1.8",
|
||||
"electron-vite": "^3.1.0",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^6.3.1",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
}
|
||||
68
src/main/index.ts
Normal file
68
src/main/index.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron'
|
||||
import { join } from 'node:path'
|
||||
import { AccountManager } from './services/account-manager'
|
||||
import { registerAccountHandlers } from './ipc/accounts.handler'
|
||||
import { registerFolderHandlers } from './ipc/folders.handler'
|
||||
import { registerMessageHandlers } from './ipc/messages.handler'
|
||||
import { registerOAuthHandlers } from './ipc/oauth.handler'
|
||||
|
||||
const accountManager = new AccountManager()
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1280,
|
||||
height: 800,
|
||||
minWidth: 900,
|
||||
minHeight: 600,
|
||||
backgroundColor: '#1e1e1e',
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
sandbox: false,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
})
|
||||
|
||||
accountManager.setMainWindow(mainWindow)
|
||||
|
||||
// Open external links in browser
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url)
|
||||
return { action: 'deny' }
|
||||
})
|
||||
|
||||
// Load the renderer
|
||||
if (process.env.ELECTRON_RENDERER_URL) {
|
||||
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
|
||||
} else {
|
||||
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
|
||||
}
|
||||
|
||||
return mainWindow
|
||||
}
|
||||
|
||||
Menu.setApplicationMenu(null)
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
await accountManager.initialize()
|
||||
|
||||
// Register all IPC handlers
|
||||
registerAccountHandlers(accountManager)
|
||||
registerFolderHandlers(accountManager)
|
||||
registerMessageHandlers(accountManager)
|
||||
registerOAuthHandlers()
|
||||
|
||||
createWindow()
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
}
|
||||
})
|
||||
24
src/main/ipc/accounts.handler.ts
Normal file
24
src/main/ipc/accounts.handler.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { registerHandler } from './registry'
|
||||
import type { AccountManager } from '../services/account-manager'
|
||||
|
||||
export function registerAccountHandlers(manager: AccountManager): void {
|
||||
registerHandler('accounts:list', async () => {
|
||||
return manager.getAccounts()
|
||||
})
|
||||
|
||||
registerHandler('accounts:add', async (config) => {
|
||||
return manager.addAccount(config)
|
||||
})
|
||||
|
||||
registerHandler('accounts:remove', async ({ accountId }) => {
|
||||
await manager.removeAccount(accountId)
|
||||
})
|
||||
|
||||
registerHandler('accounts:test', async (config) => {
|
||||
return manager.testConnection(config)
|
||||
})
|
||||
|
||||
registerHandler('accounts:connect', async ({ accountId }) => {
|
||||
return manager.connectAccount(accountId)
|
||||
})
|
||||
}
|
||||
8
src/main/ipc/folders.handler.ts
Normal file
8
src/main/ipc/folders.handler.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { registerHandler } from './registry'
|
||||
import type { AccountManager } from '../services/account-manager'
|
||||
|
||||
export function registerFolderHandlers(manager: AccountManager): void {
|
||||
registerHandler('folders:list', async ({ accountId }) => {
|
||||
return manager.listFolders(accountId)
|
||||
})
|
||||
}
|
||||
20
src/main/ipc/messages.handler.ts
Normal file
20
src/main/ipc/messages.handler.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { registerHandler } from './registry'
|
||||
import type { AccountManager } from '../services/account-manager'
|
||||
|
||||
export function registerMessageHandlers(manager: AccountManager): void {
|
||||
registerHandler('messages:list', async ({ accountId, folderId, offset, limit }) => {
|
||||
return manager.listMessages(accountId, folderId, offset, limit)
|
||||
})
|
||||
|
||||
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
||||
return manager.fetchMessageBody(accountId, folderId, messageId)
|
||||
})
|
||||
|
||||
registerHandler('messages:setFlags', async ({ accountId, folderId, messageIds, flags }) => {
|
||||
await manager.updateFlags(accountId, folderId, messageIds, flags)
|
||||
})
|
||||
|
||||
registerHandler('messages:delete', async ({ accountId, folderId, messageIds }) => {
|
||||
await manager.deleteMessages(accountId, folderId, messageIds)
|
||||
})
|
||||
}
|
||||
8
src/main/ipc/oauth.handler.ts
Normal file
8
src/main/ipc/oauth.handler.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { registerHandler } from './registry'
|
||||
import { performGmailOAuth } from '../services/oauth.service'
|
||||
|
||||
export function registerOAuthHandlers(): void {
|
||||
registerHandler('oauth:gmail', async () => {
|
||||
return await performGmailOAuth()
|
||||
})
|
||||
}
|
||||
16
src/main/ipc/registry.ts
Normal file
16
src/main/ipc/registry.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { ipcMain } from 'electron'
|
||||
import type { IpcChannelMap } from '@shared/types/ipc'
|
||||
|
||||
export function registerHandler<K extends keyof IpcChannelMap>(
|
||||
channel: K,
|
||||
handler: (payload: IpcChannelMap[K][0]) => Promise<IpcChannelMap[K][1]>
|
||||
): void {
|
||||
ipcMain.handle(channel, async (_event, payload) => {
|
||||
try {
|
||||
return await handler(payload)
|
||||
} catch (error) {
|
||||
console.error(`IPC error on ${channel}:`, error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
37
src/main/lib/html-sanitizer.ts
Normal file
37
src/main/lib/html-sanitizer.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import sanitizeHtmlLib from 'sanitize-html'
|
||||
|
||||
export function sanitizeHtml(dirty: string): string {
|
||||
return sanitizeHtmlLib(dirty, {
|
||||
allowedTags: sanitizeHtmlLib.defaults.allowedTags.concat([
|
||||
'html', 'head', 'body', 'style', 'font', 'center', 'img',
|
||||
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'span', 'div', 'p', 'br', 'hr', 'a',
|
||||
'b', 'i', 'u', 's', 'strong', 'em',
|
||||
'ul', 'ol', 'li', 'blockquote', 'pre', 'code'
|
||||
]),
|
||||
allowedAttributes: {
|
||||
'*': ['style', 'class', 'align', 'valign', 'dir'],
|
||||
'a': ['href', 'target', 'rel'],
|
||||
'img': ['src', 'alt', 'width', 'height', 'border'],
|
||||
'table': ['width', 'border', 'cellpadding', 'cellspacing', 'bgcolor'],
|
||||
'td': ['width', 'colspan', 'rowspan', 'bgcolor'],
|
||||
'th': ['width', 'colspan', 'rowspan'],
|
||||
'font': ['color', 'face', 'size']
|
||||
},
|
||||
allowedSchemes: ['http', 'https', 'mailto', 'data'],
|
||||
allowedSchemesByTag: {
|
||||
img: ['http', 'https', 'data', 'cid']
|
||||
},
|
||||
transformTags: {
|
||||
'a': (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
target: '_blank',
|
||||
rel: 'noopener noreferrer'
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
196
src/main/providers/exchange.provider.ts
Normal file
196
src/main/providers/exchange.provider.ts
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope } from '@shared/types/message'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { AccountConfig, ExchangeCredentials } from '@shared/types/account'
|
||||
import { sanitizeHtml } from '../lib/html-sanitizer'
|
||||
|
||||
// EWS imports
|
||||
import {
|
||||
ExchangeService,
|
||||
ExchangeVersion,
|
||||
WebCredentials,
|
||||
Uri,
|
||||
WellKnownFolderName,
|
||||
FolderView,
|
||||
ItemView,
|
||||
PropertySet,
|
||||
BasePropertySet,
|
||||
EmailMessageSchema,
|
||||
FolderSchema,
|
||||
Folder as EwsFolder,
|
||||
EmailMessage,
|
||||
ItemId,
|
||||
FolderId as EwsFolderId,
|
||||
SortDirection
|
||||
} from 'ews-javascript-api'
|
||||
|
||||
export class ExchangeProvider implements IEmailProvider {
|
||||
private service: ExchangeService
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private pollInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as ExchangeCredentials
|
||||
this.service = new ExchangeService(ExchangeVersion.Exchange2013)
|
||||
this.service.Credentials = new WebCredentials(creds.username, creds.password, creds.domain)
|
||||
this.service.Url = new Uri(creds.serverUrl)
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
// Test connection by fetching inbox
|
||||
const view = new FolderView(1)
|
||||
await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.offNewMail()
|
||||
this.connected = false
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this.connected
|
||||
}
|
||||
|
||||
async listFolders(): Promise<FolderListResult> {
|
||||
const view = new FolderView(100)
|
||||
view.PropertySet = new PropertySet(
|
||||
BasePropertySet.IdOnly,
|
||||
FolderSchema.DisplayName,
|
||||
FolderSchema.UnreadCount,
|
||||
FolderSchema.TotalCount,
|
||||
FolderSchema.ParentFolderId
|
||||
)
|
||||
|
||||
const result = await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
|
||||
const folders: Folder[] = result.Folders.map((f: EwsFolder) => ({
|
||||
id: f.Id.UniqueId,
|
||||
name: f.DisplayName,
|
||||
role: this.detectRole(f.DisplayName),
|
||||
parentId: null,
|
||||
unreadCount: f.UnreadCount ?? 0,
|
||||
totalCount: f.TotalCount ?? 0,
|
||||
children: []
|
||||
}))
|
||||
|
||||
return { folders }
|
||||
}
|
||||
|
||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||
const view = new ItemView(options.limit, options.offset)
|
||||
view.PropertySet = new PropertySet(
|
||||
BasePropertySet.IdOnly,
|
||||
EmailMessageSchema.Subject,
|
||||
EmailMessageSchema.From,
|
||||
EmailMessageSchema.ToRecipients,
|
||||
EmailMessageSchema.CcRecipients,
|
||||
EmailMessageSchema.DateTimeReceived,
|
||||
EmailMessageSchema.IsRead,
|
||||
EmailMessageSchema.HasAttachments,
|
||||
EmailMessageSchema.Importance
|
||||
)
|
||||
view.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending)
|
||||
|
||||
const folderId = new EwsFolderId(options.folderId)
|
||||
const result = await this.service.FindItems(folderId, view)
|
||||
|
||||
const messages: MessageEnvelope[] = result.Items.map((item: EmailMessage) => ({
|
||||
id: item.Id.UniqueId,
|
||||
folderId: options.folderId,
|
||||
subject: item.Subject ?? '(no subject)',
|
||||
from: {
|
||||
name: item.From?.Name ?? '',
|
||||
email: item.From?.Address ?? ''
|
||||
},
|
||||
to: (item.ToRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
|
||||
name: r.Name ?? '',
|
||||
email: r.Address ?? ''
|
||||
})),
|
||||
cc: (item.CcRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
|
||||
name: r.Name ?? '',
|
||||
email: r.Address ?? ''
|
||||
})),
|
||||
date: item.DateTimeReceived?.toISOString() ?? new Date().toISOString(),
|
||||
flags: {
|
||||
seen: item.IsRead ?? false,
|
||||
flagged: false,
|
||||
answered: false,
|
||||
deleted: false
|
||||
},
|
||||
hasAttachments: item.HasAttachments ?? false,
|
||||
snippet: ''
|
||||
}))
|
||||
|
||||
return { messages, total: result.TotalCount ?? messages.length }
|
||||
}
|
||||
|
||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId), new PropertySet(
|
||||
BasePropertySet.FirstClassProperties
|
||||
))
|
||||
|
||||
let html: string | null = null
|
||||
let text: string | null = null
|
||||
|
||||
const body = msg.Body?.Text ?? ''
|
||||
if (msg.Body?.BodyType === 0) { // HTML
|
||||
html = sanitizeHtml(body)
|
||||
} else {
|
||||
text = body
|
||||
}
|
||||
|
||||
return {
|
||||
id: messageId,
|
||||
html,
|
||||
text,
|
||||
inlineImages: [],
|
||||
attachments: []
|
||||
}
|
||||
}
|
||||
|
||||
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
|
||||
if (flags.seen !== undefined) {
|
||||
msg.IsRead = flags.seen
|
||||
}
|
||||
await msg.Update(1) // ConflictResolutionMode.AutoResolve
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
|
||||
await msg.Delete(1) // DeleteMode.HardDelete
|
||||
}
|
||||
}
|
||||
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
// EWS doesn't support push natively from JS — poll every 60s
|
||||
this.pollInterval = setInterval(async () => {
|
||||
// Simplified polling — in production would track last known count
|
||||
}, 60_000)
|
||||
}
|
||||
|
||||
offNewMail(): void {
|
||||
this.newMailCallback = null
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval)
|
||||
this.pollInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
private detectRole(name: string): SpecialFolderRole {
|
||||
const n = name.toLowerCase()
|
||||
if (n === 'inbox') return SpecialFolderRole.Inbox
|
||||
if (n === 'sent items' || n === 'sent') return SpecialFolderRole.Sent
|
||||
if (n === 'drafts') return SpecialFolderRole.Drafts
|
||||
if (n === 'deleted items' || n === 'trash') return SpecialFolderRole.Trash
|
||||
if (n === 'junk email' || n === 'spam') return SpecialFolderRole.Spam
|
||||
if (n === 'archive') return SpecialFolderRole.Archive
|
||||
return SpecialFolderRole.None
|
||||
}
|
||||
}
|
||||
274
src/main/providers/gmail.provider.ts
Normal file
274
src/main/providers/gmail.provider.ts
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
import { google, gmail_v1 } from 'googleapis'
|
||||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address, InlineImage, Attachment } from '@shared/types/message'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { AccountConfig, GmailCredentials } from '@shared/types/account'
|
||||
import { sanitizeHtml } from '../lib/html-sanitizer'
|
||||
|
||||
const GMAIL_CLIENT_ID = process.env.GMAIL_CLIENT_ID ?? ''
|
||||
const GMAIL_CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET ?? ''
|
||||
|
||||
export class GmailProvider implements IEmailProvider {
|
||||
private gmail: gmail_v1.Gmail
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private pollInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as GmailCredentials
|
||||
const oauth2 = new google.auth.OAuth2(GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET)
|
||||
oauth2.setCredentials({
|
||||
access_token: creds.accessToken,
|
||||
refresh_token: creds.refreshToken
|
||||
})
|
||||
this.gmail = google.gmail({ version: 'v1', auth: oauth2 })
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
// Verify connection by getting profile
|
||||
await this.gmail.users.getProfile({ userId: 'me' })
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.offNewMail()
|
||||
this.connected = false
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this.connected
|
||||
}
|
||||
|
||||
async listFolders(): Promise<FolderListResult> {
|
||||
const res = await this.gmail.users.labels.list({ userId: 'me' })
|
||||
const labels = res.data.labels ?? []
|
||||
|
||||
const folders: Folder[] = labels
|
||||
.filter((l) => l.type === 'system' || l.labelListVisibility === 'labelShow')
|
||||
.map((label) => {
|
||||
const details = label as gmail_v1.Schema$Label
|
||||
return {
|
||||
id: details.id ?? '',
|
||||
name: details.name ?? '',
|
||||
role: this.detectRole(details.id ?? ''),
|
||||
parentId: null,
|
||||
unreadCount: details.messagesUnread ?? 0,
|
||||
totalCount: details.messagesTotal ?? 0,
|
||||
children: []
|
||||
}
|
||||
})
|
||||
|
||||
return { folders }
|
||||
}
|
||||
|
||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||
const res = await this.gmail.users.messages.list({
|
||||
userId: 'me',
|
||||
labelIds: [options.folderId],
|
||||
maxResults: options.limit
|
||||
})
|
||||
|
||||
const messageRefs = res.data.messages ?? []
|
||||
const total = res.data.resultSizeEstimate ?? messageRefs.length
|
||||
|
||||
const messages: MessageEnvelope[] = []
|
||||
|
||||
for (const ref of messageRefs) {
|
||||
if (!ref.id) continue
|
||||
try {
|
||||
const msg = await this.gmail.users.messages.get({
|
||||
userId: 'me',
|
||||
id: ref.id,
|
||||
format: 'metadata',
|
||||
metadataHeaders: ['From', 'To', 'Cc', 'Subject', 'Date']
|
||||
})
|
||||
messages.push(this.convertMessage(msg.data, options.folderId))
|
||||
} catch {
|
||||
// Skip messages that fail to load
|
||||
}
|
||||
}
|
||||
|
||||
return { messages, total }
|
||||
}
|
||||
|
||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||
const msg = await this.gmail.users.messages.get({
|
||||
userId: 'me',
|
||||
id: messageId,
|
||||
format: 'full'
|
||||
})
|
||||
|
||||
const { html, text, inlineImages, attachments } = this.extractBody(msg.data)
|
||||
|
||||
return {
|
||||
id: messageId,
|
||||
html: html ? sanitizeHtml(html) : null,
|
||||
text,
|
||||
inlineImages,
|
||||
attachments
|
||||
}
|
||||
}
|
||||
|
||||
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
|
||||
const addLabels: string[] = []
|
||||
const removeLabels: string[] = []
|
||||
|
||||
if (flags.seen === true) removeLabels.push('UNREAD')
|
||||
if (flags.seen === false) addLabels.push('UNREAD')
|
||||
if (flags.flagged === true) addLabels.push('STARRED')
|
||||
if (flags.flagged === false) removeLabels.push('STARRED')
|
||||
if (flags.deleted === true) addLabels.push('TRASH')
|
||||
|
||||
if (addLabels.length > 0 || removeLabels.length > 0) {
|
||||
for (const messageId of messageIds) {
|
||||
await this.gmail.users.messages.modify({
|
||||
userId: 'me',
|
||||
id: messageId,
|
||||
requestBody: { addLabelIds: addLabels, removeLabelIds: removeLabels }
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
await this.gmail.users.messages.trash({ userId: 'me', id: messageId })
|
||||
}
|
||||
}
|
||||
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
this.pollInterval = setInterval(async () => {
|
||||
// Poll for new messages in INBOX
|
||||
try {
|
||||
const res = await this.gmail.users.messages.list({
|
||||
userId: 'me',
|
||||
labelIds: ['INBOX'],
|
||||
maxResults: 1,
|
||||
q: 'is:unread'
|
||||
})
|
||||
// In production: track historyId to detect actual new messages
|
||||
} catch {
|
||||
// Ignore polling errors
|
||||
}
|
||||
}, 60_000)
|
||||
}
|
||||
|
||||
offNewMail(): void {
|
||||
this.newMailCallback = null
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval)
|
||||
this.pollInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
private detectRole(labelId: string): SpecialFolderRole {
|
||||
switch (labelId) {
|
||||
case 'INBOX': return SpecialFolderRole.Inbox
|
||||
case 'SENT': return SpecialFolderRole.Sent
|
||||
case 'DRAFT': return SpecialFolderRole.Drafts
|
||||
case 'TRASH': return SpecialFolderRole.Trash
|
||||
case 'SPAM': return SpecialFolderRole.Spam
|
||||
default: return SpecialFolderRole.None
|
||||
}
|
||||
}
|
||||
|
||||
private convertMessage(msg: gmail_v1.Schema$Message, folderId: string): MessageEnvelope {
|
||||
const headers = msg.payload?.headers ?? []
|
||||
const getHeader = (name: string): string =>
|
||||
headers.find((h) => h.name?.toLowerCase() === name.toLowerCase())?.value ?? ''
|
||||
|
||||
const labels = msg.labelIds ?? []
|
||||
|
||||
return {
|
||||
id: msg.id ?? '',
|
||||
folderId,
|
||||
subject: getHeader('Subject') || '(no subject)',
|
||||
from: this.parseAddress(getHeader('From')),
|
||||
to: this.parseAddressList(getHeader('To')),
|
||||
cc: this.parseAddressList(getHeader('Cc')),
|
||||
date: new Date(parseInt(msg.internalDate ?? '0')).toISOString(),
|
||||
flags: {
|
||||
seen: !labels.includes('UNREAD'),
|
||||
flagged: labels.includes('STARRED'),
|
||||
answered: false,
|
||||
deleted: labels.includes('TRASH')
|
||||
},
|
||||
hasAttachments: this.checkHasAttachments(msg.payload),
|
||||
snippet: msg.snippet ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
private parseAddress(raw: string): Address {
|
||||
const match = raw.match(/^(.*?)\s*<(.+?)>$/)
|
||||
if (match) {
|
||||
return { name: match[1].replace(/^"|"$/g, '').trim(), email: match[2] }
|
||||
}
|
||||
return { name: '', email: raw.trim() }
|
||||
}
|
||||
|
||||
private parseAddressList(raw: string): Address[] {
|
||||
if (!raw) return []
|
||||
return raw.split(',').map((s) => this.parseAddress(s.trim()))
|
||||
}
|
||||
|
||||
private checkHasAttachments(payload?: gmail_v1.Schema$MessagePart | null): boolean {
|
||||
if (!payload) return false
|
||||
if (payload.filename && payload.filename.length > 0) return true
|
||||
if (payload.parts) {
|
||||
return payload.parts.some((p) => this.checkHasAttachments(p))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private extractBody(msg: gmail_v1.Schema$Message): {
|
||||
html: string | null
|
||||
text: string | null
|
||||
inlineImages: InlineImage[]
|
||||
attachments: Attachment[]
|
||||
} {
|
||||
let html: string | null = null
|
||||
let text: string | null = null
|
||||
const inlineImages: InlineImage[] = []
|
||||
const attachments: Attachment[] = []
|
||||
|
||||
const processPart = (part: gmail_v1.Schema$MessagePart) => {
|
||||
if (part.mimeType === 'text/html' && part.body?.data) {
|
||||
html = Buffer.from(part.body.data, 'base64url').toString('utf-8')
|
||||
} else if (part.mimeType === 'text/plain' && part.body?.data && !text) {
|
||||
text = Buffer.from(part.body.data, 'base64url').toString('utf-8')
|
||||
} else if (part.filename && part.filename.length > 0) {
|
||||
const headers = part.headers ?? []
|
||||
const contentId = headers.find((h) => h.name?.toLowerCase() === 'content-id')?.value
|
||||
const disposition = headers.find((h) => h.name?.toLowerCase() === 'content-disposition')?.value
|
||||
|
||||
if (disposition?.includes('inline') && contentId) {
|
||||
// Inline image — would need to fetch attachment data
|
||||
inlineImages.push({
|
||||
cid: contentId.replace(/[<>]/g, ''),
|
||||
contentType: part.mimeType ?? 'application/octet-stream',
|
||||
data: '' // Would need separate API call to fetch
|
||||
})
|
||||
} else {
|
||||
attachments.push({
|
||||
id: part.body?.attachmentId ?? '',
|
||||
filename: part.filename,
|
||||
contentType: part.mimeType ?? 'application/octet-stream',
|
||||
size: part.body?.size ?? 0
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (part.parts) {
|
||||
part.parts.forEach(processPart)
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.payload) {
|
||||
processPart(msg.payload)
|
||||
}
|
||||
|
||||
return { html, text, inlineImages, attachments }
|
||||
}
|
||||
}
|
||||
290
src/main/providers/imap.provider.ts
Normal file
290
src/main/providers/imap.provider.ts
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
import { ImapFlow } from 'imapflow'
|
||||
import { simpleParser } from 'mailparser'
|
||||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address } from '@shared/types/message'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
import { sanitizeHtml } from '../lib/html-sanitizer'
|
||||
|
||||
// imapflow MailboxObject type
|
||||
interface ImapMailbox {
|
||||
name: string
|
||||
path: string
|
||||
specialUse?: string
|
||||
folders?: ImapMailbox[]
|
||||
}
|
||||
|
||||
// imapflow BodyStructure type
|
||||
interface BodyPart {
|
||||
part?: string
|
||||
type?: string
|
||||
subtype?: string
|
||||
disposition?: string
|
||||
parameters?: Record<string, string>
|
||||
id?: string
|
||||
encoding?: string
|
||||
childNodes?: BodyPart[]
|
||||
}
|
||||
|
||||
export class ImapProvider implements IEmailProvider {
|
||||
private client: ImapFlow
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as ImapCredentials
|
||||
this.client = new ImapFlow({
|
||||
host: creds.host,
|
||||
port: creds.port,
|
||||
secure: creds.secure,
|
||||
auth: {
|
||||
user: creds.username,
|
||||
pass: creds.password
|
||||
},
|
||||
logger: false
|
||||
})
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
await this.client.connect()
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.offNewMail()
|
||||
if (this.connected) {
|
||||
try {
|
||||
await this.client.logout()
|
||||
} catch { /* ignore */ }
|
||||
this.connected = false
|
||||
}
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this.connected
|
||||
}
|
||||
|
||||
async listFolders(): Promise<FolderListResult> {
|
||||
// listTree() returns { root: true, folders: ImapMailbox[] }
|
||||
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||
const folders = this.convertMailboxArray(tree.folders ?? [])
|
||||
return { folders }
|
||||
}
|
||||
|
||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||
const lock = await this.client.getMailboxLock(options.folderId)
|
||||
try {
|
||||
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
|
||||
if (total === 0) return { messages: [], total: 0 }
|
||||
|
||||
// IMAP sequence numbers are 1-based, newest = highest number
|
||||
const end = Math.max(1, total - options.offset)
|
||||
const start = Math.max(1, end - options.limit + 1)
|
||||
|
||||
if (start > total) return { messages: [], total }
|
||||
|
||||
const messages: MessageEnvelope[] = []
|
||||
|
||||
for await (const msg of this.client.fetch(`${start}:${end}`, {
|
||||
uid: true,
|
||||
envelope: true,
|
||||
flags: true,
|
||||
bodyStructure: true
|
||||
})) {
|
||||
messages.push(this.convertMessage(msg, options.folderId))
|
||||
}
|
||||
|
||||
// Newest first
|
||||
messages.reverse()
|
||||
|
||||
return { messages, total }
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||
const lock = await this.client.getMailboxLock(folderId)
|
||||
try {
|
||||
// Download full RFC822 source and parse with mailparser
|
||||
const download = await this.client.download(messageId, undefined, { uid: true })
|
||||
if (!download) {
|
||||
return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] }
|
||||
}
|
||||
|
||||
const parsed = await simpleParser(download.content)
|
||||
|
||||
const inlineImages: InlineImage[] = []
|
||||
const attachments: Attachment[] = []
|
||||
|
||||
for (const att of parsed.attachments) {
|
||||
if (att.contentDisposition === 'inline' && att.contentId && att.contentType.startsWith('image/')) {
|
||||
inlineImages.push({
|
||||
cid: att.contentId.replace(/[<>]/g, ''),
|
||||
contentType: att.contentType,
|
||||
data: att.content.toString('base64')
|
||||
})
|
||||
} else if (att.contentDisposition === 'attachment' || att.filename) {
|
||||
attachments.push({
|
||||
id: att.checksum ?? att.filename ?? '',
|
||||
filename: att.filename ?? 'attachment',
|
||||
contentType: att.contentType,
|
||||
size: att.size ?? 0
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: messageId,
|
||||
html: parsed.html ? sanitizeHtml(parsed.html) : null,
|
||||
text: parsed.text ?? null,
|
||||
inlineImages,
|
||||
attachments
|
||||
}
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
|
||||
const lock = await this.client.getMailboxLock(folderId)
|
||||
try {
|
||||
const uidSet = messageIds.join(',')
|
||||
const addFlags: string[] = []
|
||||
const removeFlags: string[] = []
|
||||
|
||||
if (flags.seen === true) addFlags.push('\\Seen')
|
||||
if (flags.seen === false) removeFlags.push('\\Seen')
|
||||
if (flags.flagged === true) addFlags.push('\\Flagged')
|
||||
if (flags.flagged === false) removeFlags.push('\\Flagged')
|
||||
if (flags.answered === true) addFlags.push('\\Answered')
|
||||
if (flags.deleted === true) addFlags.push('\\Deleted')
|
||||
|
||||
if (addFlags.length > 0) {
|
||||
await this.client.messageFlagsAdd(uidSet, addFlags, { uid: true })
|
||||
}
|
||||
if (removeFlags.length > 0) {
|
||||
await this.client.messageFlagsRemove(uidSet, removeFlags, { uid: true })
|
||||
}
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
|
||||
const lock = await this.client.getMailboxLock(folderId)
|
||||
try {
|
||||
const uidSet = messageIds.join(',')
|
||||
await this.client.messageDelete(uidSet, { uid: true })
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
|
||||
if (this.newMailCallback && data.count > data.prevCount) {
|
||||
this.newMailCallback(data.path, {
|
||||
id: '',
|
||||
folderId: data.path,
|
||||
subject: 'New message',
|
||||
from: { name: '', email: '' },
|
||||
to: [],
|
||||
cc: [],
|
||||
date: new Date().toISOString(),
|
||||
flags: { seen: false, flagged: false, answered: false, deleted: false },
|
||||
hasAttachments: false,
|
||||
snippet: ''
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
offNewMail(): void {
|
||||
this.newMailCallback = null
|
||||
this.client.removeAllListeners('exists')
|
||||
}
|
||||
|
||||
// ---- Private helpers ----
|
||||
|
||||
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
|
||||
return mailboxes.map((mb) => ({
|
||||
id: mb.path,
|
||||
name: mb.name,
|
||||
role: this.detectFolderRole(mb.specialUse, mb.name),
|
||||
parentId,
|
||||
unreadCount: 0,
|
||||
totalCount: 0,
|
||||
children: mb.folders ? this.convertMailboxArray(mb.folders, mb.path) : []
|
||||
}))
|
||||
}
|
||||
|
||||
private detectFolderRole(specialUse?: string, name?: string): SpecialFolderRole {
|
||||
if (specialUse) {
|
||||
const u = specialUse.toLowerCase()
|
||||
if (u.includes('inbox')) return SpecialFolderRole.Inbox
|
||||
if (u.includes('sent')) return SpecialFolderRole.Sent
|
||||
if (u.includes('draft')) return SpecialFolderRole.Drafts
|
||||
if (u.includes('trash') || u.includes('deleted')) return SpecialFolderRole.Trash
|
||||
if (u.includes('junk') || u.includes('spam')) return SpecialFolderRole.Spam
|
||||
if (u.includes('archive') || u.includes('all')) return SpecialFolderRole.Archive
|
||||
}
|
||||
if (name) {
|
||||
const n = name.toLowerCase()
|
||||
if (n === 'inbox') return SpecialFolderRole.Inbox
|
||||
if (n === 'sent' || n === 'sent mail' || n === 'sent items') return SpecialFolderRole.Sent
|
||||
if (n === 'drafts' || n === 'draft') return SpecialFolderRole.Drafts
|
||||
if (n === 'trash' || n === 'deleted items' || n === 'deleted messages') return SpecialFolderRole.Trash
|
||||
if (n === 'spam' || n === 'junk' || n === 'junk e-mail') return SpecialFolderRole.Spam
|
||||
if (n === 'archive' || n === 'all mail') return SpecialFolderRole.Archive
|
||||
}
|
||||
return SpecialFolderRole.None
|
||||
}
|
||||
|
||||
private convertMessage(msg: unknown, folderId: string): MessageEnvelope {
|
||||
const m = msg as {
|
||||
uid: number
|
||||
envelope: {
|
||||
subject?: string
|
||||
from?: Array<{ name?: string; address?: string }>
|
||||
to?: Array<{ name?: string; address?: string }>
|
||||
cc?: Array<{ name?: string; address?: string }>
|
||||
date?: Date
|
||||
}
|
||||
flags: Set<string>
|
||||
bodyStructure?: BodyPart
|
||||
}
|
||||
|
||||
const addr = (list?: Array<{ name?: string; address?: string }>): Address[] =>
|
||||
(list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' }))
|
||||
|
||||
const flags = m.flags ?? new Set<string>()
|
||||
|
||||
return {
|
||||
id: String(m.uid),
|
||||
folderId,
|
||||
subject: m.envelope?.subject ?? '(no subject)',
|
||||
from: addr(m.envelope?.from)[0] ?? { name: '', email: '' },
|
||||
to: addr(m.envelope?.to),
|
||||
cc: addr(m.envelope?.cc),
|
||||
date: m.envelope?.date?.toISOString() ?? new Date().toISOString(),
|
||||
flags: {
|
||||
seen: flags.has('\\Seen'),
|
||||
flagged: flags.has('\\Flagged'),
|
||||
answered: flags.has('\\Answered'),
|
||||
deleted: flags.has('\\Deleted')
|
||||
},
|
||||
hasAttachments: this.hasAttachments(m.bodyStructure),
|
||||
snippet: ''
|
||||
}
|
||||
}
|
||||
|
||||
private hasAttachments(node?: BodyPart): boolean {
|
||||
if (!node) return false
|
||||
if (node.disposition === 'attachment') return true
|
||||
if (node.childNodes) return node.childNodes.some((c) => this.hasAttachments(c))
|
||||
return false
|
||||
}
|
||||
}
|
||||
188
src/main/services/account-manager.ts
Normal file
188
src/main/services/account-manager.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import type { AccountConfig } from '@shared/types/account'
|
||||
import { AccountType } from '@shared/types/account'
|
||||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags } from '@shared/types/message'
|
||||
import { ImapProvider } from '../providers/imap.provider'
|
||||
import { ExchangeProvider } from '../providers/exchange.provider'
|
||||
import { GmailProvider } from '../providers/gmail.provider'
|
||||
import { CredentialStore } from './credential-store'
|
||||
import Store from 'electron-store'
|
||||
|
||||
interface AccountStoreSchema {
|
||||
accounts: Omit<AccountConfig, 'credentials'>[]
|
||||
}
|
||||
|
||||
export class AccountManager {
|
||||
private providers = new Map<string, IEmailProvider>()
|
||||
private store: Store<AccountStoreSchema>
|
||||
private credentialStore: CredentialStore
|
||||
private mainWindow: BrowserWindow | null = null
|
||||
|
||||
constructor() {
|
||||
this.store = new Store<AccountStoreSchema>({
|
||||
name: 'accounts',
|
||||
defaults: { accounts: [] }
|
||||
})
|
||||
this.credentialStore = new CredentialStore()
|
||||
}
|
||||
|
||||
setMainWindow(win: BrowserWindow): void {
|
||||
this.mainWindow = win
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
await this.credentialStore.load()
|
||||
}
|
||||
|
||||
getAccounts(): AccountConfig[] {
|
||||
const accounts = this.store.get('accounts', [])
|
||||
return accounts.map((acc) => ({
|
||||
...acc,
|
||||
credentials: {} as AccountConfig['credentials']
|
||||
}))
|
||||
}
|
||||
|
||||
async addAccount(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
|
||||
await this.credentialStore.save(config.id, JSON.stringify(config.credentials))
|
||||
|
||||
const { credentials: _, ...safeConfig } = config
|
||||
const accounts = this.store.get('accounts', [])
|
||||
accounts.push(safeConfig)
|
||||
this.store.set('accounts', accounts)
|
||||
|
||||
this.providers.set(config.id, provider)
|
||||
this.setupNewMailListener(config.id, provider)
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
async removeAccount(accountId: string): Promise<void> {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (provider) {
|
||||
provider.offNewMail()
|
||||
await provider.disconnect()
|
||||
this.providers.delete(accountId)
|
||||
}
|
||||
await this.credentialStore.remove(accountId)
|
||||
|
||||
const accounts = this.store.get('accounts', [])
|
||||
this.store.set('accounts', accounts.filter((a) => a.id !== accountId))
|
||||
}
|
||||
|
||||
async testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
await provider.disconnect()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
async connectAccount(accountId: string): Promise<{ success: boolean; error?: string }> {
|
||||
if (this.providers.has(accountId)) {
|
||||
return { success: true }
|
||||
}
|
||||
try {
|
||||
const accounts = this.store.get('accounts', [])
|
||||
const accMeta = accounts.find((a) => a.id === accountId)
|
||||
if (!accMeta) return { success: false, error: 'Account not found' }
|
||||
|
||||
const credRaw = this.credentialStore.get(accountId)
|
||||
if (!credRaw) return { success: false, 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)
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
async listFolders(accountId: string): Promise<FolderListResult> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.listFolders()
|
||||
}
|
||||
|
||||
async listMessages(
|
||||
accountId: string,
|
||||
folderId: string,
|
||||
offset: number,
|
||||
limit: number
|
||||
): Promise<MessageListResult> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.listMessages({ folderId, offset, limit })
|
||||
}
|
||||
|
||||
async fetchMessageBody(
|
||||
accountId: string,
|
||||
folderId: string,
|
||||
messageId: string
|
||||
): Promise<MessageBody> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.fetchMessageBody(folderId, messageId)
|
||||
}
|
||||
|
||||
async updateFlags(
|
||||
accountId: string,
|
||||
folderId: string,
|
||||
messageIds: string[],
|
||||
flags: Partial<MessageFlags>
|
||||
): Promise<void> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.updateFlags(folderId, messageIds, flags)
|
||||
}
|
||||
|
||||
async deleteMessages(
|
||||
accountId: string,
|
||||
folderId: string,
|
||||
messageIds: string[]
|
||||
): Promise<void> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.deleteMessages(folderId, messageIds)
|
||||
}
|
||||
|
||||
private getProvider(accountId: string): IEmailProvider {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
||||
return provider
|
||||
}
|
||||
|
||||
private createProvider(config: AccountConfig): IEmailProvider {
|
||||
switch (config.type) {
|
||||
case AccountType.IMAP:
|
||||
return new ImapProvider(config)
|
||||
case AccountType.Exchange:
|
||||
return new ExchangeProvider(config)
|
||||
case AccountType.Gmail:
|
||||
return new GmailProvider(config)
|
||||
default:
|
||||
throw new Error(`Unknown account type: ${config.type}`)
|
||||
}
|
||||
}
|
||||
|
||||
private setupNewMailListener(accountId: string, provider: IEmailProvider): void {
|
||||
provider.onNewMail((folderId, envelope) => {
|
||||
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||||
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
56
src/main/services/credential-store.ts
Normal file
56
src/main/services/credential-store.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { safeStorage, app } from 'electron'
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { existsSync } from 'node:fs'
|
||||
|
||||
export class CredentialStore {
|
||||
private filePath: string
|
||||
private data: Record<string, string> = {}
|
||||
|
||||
constructor() {
|
||||
this.filePath = join(app.getPath('userData'), 'credentials.json')
|
||||
}
|
||||
|
||||
async load(): Promise<void> {
|
||||
try {
|
||||
if (!existsSync(this.filePath)) return
|
||||
const raw = await readFile(this.filePath, 'utf-8')
|
||||
const parsed = JSON.parse(raw) as Record<string, string>
|
||||
for (const [key, encrypted] of Object.entries(parsed)) {
|
||||
try {
|
||||
this.data[key] = safeStorage.decryptString(Buffer.from(encrypted, 'base64'))
|
||||
} catch {
|
||||
console.warn(`Failed to decrypt credential for ${key}`)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
this.data = {}
|
||||
}
|
||||
}
|
||||
|
||||
async save(accountId: string, secret: string): Promise<void> {
|
||||
this.data[accountId] = secret
|
||||
await this.persist()
|
||||
}
|
||||
|
||||
get(accountId: string): string | undefined {
|
||||
return this.data[accountId]
|
||||
}
|
||||
|
||||
async remove(accountId: string): Promise<void> {
|
||||
delete this.data[accountId]
|
||||
await this.persist()
|
||||
}
|
||||
|
||||
private async persist(): Promise<void> {
|
||||
const encrypted: Record<string, string> = {}
|
||||
for (const [key, value] of Object.entries(this.data)) {
|
||||
encrypted[key] = safeStorage.encryptString(value).toString('base64')
|
||||
}
|
||||
const dir = dirname(this.filePath)
|
||||
if (!existsSync(dir)) {
|
||||
await mkdir(dir, { recursive: true })
|
||||
}
|
||||
await writeFile(this.filePath, JSON.stringify(encrypted, null, 2), 'utf-8')
|
||||
}
|
||||
}
|
||||
71
src/main/services/oauth.service.ts
Normal file
71
src/main/services/oauth.service.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import { google } from 'googleapis'
|
||||
|
||||
const GMAIL_CLIENT_ID = process.env.GMAIL_CLIENT_ID ?? ''
|
||||
const GMAIL_CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET ?? ''
|
||||
const REDIRECT_URI = 'http://localhost'
|
||||
|
||||
export interface OAuthTokens {
|
||||
email: string
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
export async function performGmailOAuth(): Promise<OAuthTokens | null> {
|
||||
const oauth2Client = new google.auth.OAuth2(GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET, REDIRECT_URI)
|
||||
|
||||
const authUrl = oauth2Client.generateAuthUrl({
|
||||
access_type: 'offline',
|
||||
prompt: 'consent',
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/gmail.readonly',
|
||||
'https://www.googleapis.com/auth/gmail.modify',
|
||||
'https://www.googleapis.com/auth/userinfo.email'
|
||||
]
|
||||
})
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const authWindow = new BrowserWindow({
|
||||
width: 600,
|
||||
height: 700,
|
||||
show: true,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true
|
||||
}
|
||||
})
|
||||
|
||||
authWindow.loadURL(authUrl)
|
||||
|
||||
authWindow.webContents.on('will-redirect', async (_event, url) => {
|
||||
const urlObj = new URL(url)
|
||||
const code = urlObj.searchParams.get('code')
|
||||
|
||||
if (code) {
|
||||
try {
|
||||
const { tokens } = await oauth2Client.getToken(code)
|
||||
oauth2Client.setCredentials(tokens)
|
||||
|
||||
// Get user email
|
||||
const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client })
|
||||
const userInfo = await oauth2.userinfo.get()
|
||||
|
||||
authWindow.close()
|
||||
resolve({
|
||||
email: userInfo.data.email ?? '',
|
||||
accessToken: tokens.access_token ?? '',
|
||||
refreshToken: tokens.refresh_token ?? ''
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('OAuth token exchange failed:', error)
|
||||
authWindow.close()
|
||||
resolve(null)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
authWindow.on('closed', () => {
|
||||
resolve(null)
|
||||
})
|
||||
})
|
||||
}
|
||||
7
src/preload/index.d.ts
vendored
Normal file
7
src/preload/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import type { Api } from './index'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
api: Api
|
||||
}
|
||||
}
|
||||
29
src/preload/index.ts
Normal file
29
src/preload/index.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
import type { IpcChannelMap, IpcEventMap } from '@shared/types/ipc'
|
||||
|
||||
export type Api = {
|
||||
invoke<K extends keyof IpcChannelMap>(
|
||||
channel: K,
|
||||
...args: IpcChannelMap[K][0] extends void ? [] : [IpcChannelMap[K][0]]
|
||||
): Promise<IpcChannelMap[K][1]>
|
||||
|
||||
on<K extends keyof IpcEventMap>(
|
||||
channel: K,
|
||||
callback: (data: IpcEventMap[K]) => void
|
||||
): () => void
|
||||
}
|
||||
|
||||
const api: Api = {
|
||||
invoke(channel: string, ...args: unknown[]) {
|
||||
return ipcRenderer.invoke(channel, ...args)
|
||||
},
|
||||
on(channel: string, callback: (data: unknown) => void) {
|
||||
const listener = (_event: Electron.IpcRendererEvent, data: unknown) => callback(data as never)
|
||||
ipcRenderer.on(channel, listener)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(channel, listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('api', api)
|
||||
12
src/renderer/index.html
Normal file
12
src/renderer/index.html
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vue Mail</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
14
src/renderer/src/App.vue
Normal file
14
src/renderer/src/App.vue
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { useAccountsStore } from './stores/accounts.store'
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
|
||||
onMounted(() => {
|
||||
accountsStore.loadAccounts()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
104
src/renderer/src/assets/styles/base.css
Normal file
104
src/renderer/src/assets/styles/base.css
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-primary);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
button {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 6px 10px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:focus,
|
||||
select:focus,
|
||||
textarea:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-hover);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--border-light);
|
||||
}
|
||||
|
||||
/* Utility classes */
|
||||
.truncate {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
border: 0;
|
||||
}
|
||||
43
src/renderer/src/assets/styles/variables.css
Normal file
43
src/renderer/src/assets/styles/variables.css
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
:root {
|
||||
--bg-primary: #1e1e1e;
|
||||
--bg-secondary: #252526;
|
||||
--bg-tertiary: #2d2d30;
|
||||
--bg-hover: #3e3e42;
|
||||
--bg-selected: #37373d;
|
||||
--bg-input: #3c3c3c;
|
||||
|
||||
--text-primary: #e0e0e0;
|
||||
--text-secondary: #a0a0a0;
|
||||
--text-muted: #6e6e6e;
|
||||
|
||||
--accent: #a8e600;
|
||||
--accent-hover: #c5ff1a;
|
||||
--accent-muted: rgba(168, 230, 0, 0.15);
|
||||
--accent-text: #1e1e1e;
|
||||
|
||||
--border: #3e3e42;
|
||||
--border-light: #4e4e52;
|
||||
|
||||
--danger: #f44747;
|
||||
--warning: #cca700;
|
||||
--success: #89d185;
|
||||
|
||||
--radius-sm: 4px;
|
||||
--radius-md: 6px;
|
||||
--radius-lg: 8px;
|
||||
|
||||
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.5);
|
||||
|
||||
--titlebar-height: 32px;
|
||||
--statusbar-height: 24px;
|
||||
--sidebar-width: 48px;
|
||||
--folderpane-width: 240px;
|
||||
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
--font-mono: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', monospace;
|
||||
|
||||
--transition-fast: 150ms ease;
|
||||
--transition-normal: 250ms ease;
|
||||
}
|
||||
275
src/renderer/src/components/accounts/AddAccountDialog.vue
Normal file
275
src/renderer/src/components/accounts/AddAccountDialog.vue
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { AccountType } from '@shared/types/account'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
}>()
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
|
||||
const step = ref<'credentials' | 'testing'>('credentials')
|
||||
const error = ref('')
|
||||
const testing = ref(false)
|
||||
|
||||
const imapHost = ref('')
|
||||
const imapPort = ref(993)
|
||||
const imapSecure = ref(true)
|
||||
const imapUsername = ref('')
|
||||
const imapPassword = ref('')
|
||||
const imapLabel = ref('')
|
||||
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
}
|
||||
|
||||
async function handleSubmit(): Promise<void> {
|
||||
testing.value = true
|
||||
error.value = ''
|
||||
step.value = 'testing'
|
||||
|
||||
try {
|
||||
const credentials: ImapCredentials = {
|
||||
host: imapHost.value,
|
||||
port: imapPort.value,
|
||||
secure: imapSecure.value,
|
||||
username: imapUsername.value,
|
||||
password: imapPassword.value
|
||||
}
|
||||
const config: AccountConfig = {
|
||||
id: generateId(),
|
||||
type: AccountType.IMAP,
|
||||
label: imapLabel.value || imapUsername.value,
|
||||
email: imapUsername.value,
|
||||
credentials
|
||||
}
|
||||
|
||||
const testResult = await accountsStore.testConnection(config)
|
||||
if (!testResult.success) {
|
||||
error.value = testResult.error ?? 'Ошибка подключения'
|
||||
step.value = 'credentials'
|
||||
return
|
||||
}
|
||||
|
||||
const addResult = await accountsStore.addAccount(config)
|
||||
if (addResult.success) {
|
||||
emit('close')
|
||||
} else {
|
||||
error.value = addResult.error ?? 'Не удалось добавить аккаунт'
|
||||
step.value = 'credentials'
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = (err as Error).message
|
||||
step.value = 'credentials'
|
||||
} finally {
|
||||
testing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const isFormValid = computed(() => imapHost.value && imapUsername.value && imapPassword.value)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="dialog-overlay" @click.self="emit('close')">
|
||||
<div class="dialog">
|
||||
<div class="dialog-header">
|
||||
<h2>Добавить аккаунт</h2>
|
||||
<button class="close-btn" @click="emit('close')">×</button>
|
||||
</div>
|
||||
|
||||
<!-- Форма учётных данных -->
|
||||
<div v-if="step === 'credentials'" class="dialog-body">
|
||||
<div v-if="error" class="error-msg">{{ error }}</div>
|
||||
|
||||
<form @submit.prevent="handleSubmit">
|
||||
<div class="form-group">
|
||||
<label>Название (необязательно)</label>
|
||||
<input v-model="imapLabel" type="text" placeholder="Моя почта" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group flex-1">
|
||||
<label>IMAP сервер</label>
|
||||
<input v-model="imapHost" type="text" placeholder="imap.example.com" required />
|
||||
</div>
|
||||
<div class="form-group" style="width: 80px">
|
||||
<label>Порт</label>
|
||||
<input v-model.number="imapPort" type="number" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="checkbox-label">
|
||||
<input v-model="imapSecure" type="checkbox" />
|
||||
Использовать SSL/TLS
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Имя пользователя / Email</label>
|
||||
<input v-model="imapUsername" type="text" placeholder="user@example.com" required />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Пароль</label>
|
||||
<input v-model="imapPassword" type="password" required />
|
||||
</div>
|
||||
<button type="submit" class="submit-btn" :disabled="!isFormValid || testing">
|
||||
{{ testing ? 'Подключение...' : 'Добавить аккаунт' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Состояние проверки -->
|
||||
<div v-if="step === 'testing'" class="dialog-body testing-state">
|
||||
<div class="spinner" />
|
||||
<span>Проверка подключения...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.dialog {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
width: 480px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.dialog-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dialog-header h2 {
|
||||
flex: 1;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 16px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.dialog-body {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.error-msg {
|
||||
padding: 8px 12px;
|
||||
background: rgba(244, 71, 71, 0.15);
|
||||
border: 1px solid var(--danger);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--danger);
|
||||
font-size: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.form-group input[type="text"],
|
||||
.form-group input[type="password"],
|
||||
.form-group input[type="number"] {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.flex-1 {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.checkbox-label {
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkbox-label input[type="checkbox"] {
|
||||
width: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
border-radius: var(--radius-md);
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
margin-top: 8px;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
.submit-btn:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.submit-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.testing-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 40px 20px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
203
src/renderer/src/components/layout/AppShell.vue
Normal file
203
src/renderer/src/components/layout/AppShell.vue
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import StatusBar from './StatusBar.vue'
|
||||
import AccountSwitcher from '../sidebar/AccountSwitcher.vue'
|
||||
import FolderTree from '../sidebar/FolderTree.vue'
|
||||
import MessageList from '../messages/MessageList.vue'
|
||||
import MessagePreview from '../preview/MessagePreview.vue'
|
||||
import AddAccountDialog from '../accounts/AddAccountDialog.vue'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
const showAddAccount = ref(false)
|
||||
const folderPaneWidth = ref(240)
|
||||
const messagePaneWidth = ref(360)
|
||||
|
||||
function onAddAccount(): void {
|
||||
showAddAccount.value = true
|
||||
}
|
||||
|
||||
let resizing: 'folder' | 'message' | null = null
|
||||
let startX = 0
|
||||
let startWidth = 0
|
||||
|
||||
function startResize(pane: 'folder' | 'message', e: MouseEvent): void {
|
||||
resizing = pane
|
||||
startX = e.clientX
|
||||
startWidth = pane === 'folder' ? folderPaneWidth.value : messagePaneWidth.value
|
||||
document.addEventListener('mousemove', onMouseMove)
|
||||
document.addEventListener('mouseup', stopResize)
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
}
|
||||
|
||||
function onMouseMove(e: MouseEvent): void {
|
||||
if (!resizing) return
|
||||
const delta = e.clientX - startX
|
||||
if (resizing === 'folder') {
|
||||
folderPaneWidth.value = Math.max(180, Math.min(400, startWidth + delta))
|
||||
} else {
|
||||
messagePaneWidth.value = Math.max(240, Math.min(600, startWidth + delta))
|
||||
}
|
||||
}
|
||||
|
||||
function stopResize(): void {
|
||||
resizing = null
|
||||
document.removeEventListener('mousemove', onMouseMove)
|
||||
document.removeEventListener('mouseup', stopResize)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-shell">
|
||||
<div class="content-area">
|
||||
<div class="account-bar">
|
||||
<AccountSwitcher @add-account="onAddAccount" />
|
||||
</div>
|
||||
|
||||
<div class="folder-pane" :style="{ width: folderPaneWidth + 'px' }">
|
||||
<FolderTree />
|
||||
</div>
|
||||
|
||||
<div class="resize-handle" @mousedown="startResize('folder', $event)" />
|
||||
|
||||
<div class="message-pane" :style="{ width: messagePaneWidth + 'px' }">
|
||||
<MessageList />
|
||||
</div>
|
||||
|
||||
<div class="resize-handle" @mousedown="startResize('message', $event)" />
|
||||
|
||||
<div class="preview-pane">
|
||||
<MessagePreview />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<StatusBar class="statusbar" />
|
||||
|
||||
<AddAccountDialog
|
||||
v-if="showAddAccount"
|
||||
@close="showAddAccount = false"
|
||||
/>
|
||||
|
||||
<!-- Пустое состояние: нет аккаунтов -->
|
||||
<div v-if="accountsStore.accounts.length === 0 && !accountsStore.loading && !showAddAccount" class="empty-state">
|
||||
<div class="empty-content">
|
||||
<div class="empty-icon">✉</div>
|
||||
<h2>Добро пожаловать в Vue Mail</h2>
|
||||
<p>Добавьте почтовый аккаунт для начала работы</p>
|
||||
<button class="add-btn" @click="onAddAccount">
|
||||
Добавить аккаунт
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.content-area {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.account-bar {
|
||||
width: var(--sidebar-width);
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-primary);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.folder-pane {
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-secondary);
|
||||
overflow-y: auto;
|
||||
min-width: 180px;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.message-pane {
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-secondary);
|
||||
overflow: hidden;
|
||||
min-width: 240px;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.preview-pane {
|
||||
flex: 1;
|
||||
background: var(--bg-primary);
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.resize-handle {
|
||||
width: 4px;
|
||||
flex-shrink: 0;
|
||||
background: var(--border);
|
||||
cursor: col-resize;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
.resize-handle:hover,
|
||||
.resize-handle:active {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.statusbar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
position: fixed;
|
||||
inset: 0 0 var(--statusbar-height) 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--bg-primary);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.empty-content {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 16px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.empty-content h2 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.empty-content p {
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.add-btn {
|
||||
padding: 10px 24px;
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
border-radius: var(--radius-md);
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.add-btn:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
</style>
|
||||
69
src/renderer/src/components/layout/StatusBar.vue
Normal file
69
src/renderer/src/components/layout/StatusBar.vue
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import { useFoldersStore } from '../../stores/folders.store'
|
||||
import { useMessagesStore } from '../../stores/messages.store'
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
const foldersStore = useFoldersStore()
|
||||
const messagesStore = useMessagesStore()
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (!accountsStore.activeAccount) return 'Аккаунт не выбран'
|
||||
const folder = foldersStore.activeFolder
|
||||
if (!folder) return accountsStore.activeAccount.email
|
||||
return `${folder.name} — ${messagesStore.totalCount} сообщений`
|
||||
})
|
||||
|
||||
const connectionText = computed(() => {
|
||||
if (!accountsStore.activeAccountId) return ''
|
||||
const status = accountsStore.connectionStatus[accountsStore.activeAccountId]
|
||||
if (!status) return 'Отключено'
|
||||
return status.connected ? 'Подключено' : `Ошибка: ${status.error ?? 'Отключено'}`
|
||||
})
|
||||
|
||||
const isConnected = computed(() => {
|
||||
if (!accountsStore.activeAccountId) return false
|
||||
return accountsStore.connectionStatus[accountsStore.activeAccountId]?.connected ?? false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="statusbar">
|
||||
<span class="status-text">{{ statusText }}</span>
|
||||
<span class="connection-status">
|
||||
<span class="status-dot" :class="{ connected: isConnected }" />
|
||||
{{ connectionText }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.statusbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 12px;
|
||||
background: var(--bg-tertiary);
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--danger);
|
||||
}
|
||||
|
||||
.status-dot.connected {
|
||||
background: var(--success);
|
||||
}
|
||||
</style>
|
||||
81
src/renderer/src/components/layout/TitleBar.vue
Normal file
81
src/renderer/src/components/layout/TitleBar.vue
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<script setup lang="ts">
|
||||
function minimize(): void {
|
||||
(window.api as any).invoke('window:minimize')
|
||||
}
|
||||
|
||||
function maximize(): void {
|
||||
(window.api as any).invoke('window:maximize')
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
(window.api as any).invoke('window:close')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="titlebar">
|
||||
<div class="titlebar-drag">
|
||||
<span class="app-title">Vue Mail</span>
|
||||
</div>
|
||||
<div class="titlebar-controls">
|
||||
<button class="control-btn minimize" title="Свернуть" @click="minimize">
|
||||
─
|
||||
</button>
|
||||
<button class="control-btn maximize" title="Развернуть" @click="maximize">
|
||||
□
|
||||
</button>
|
||||
<button class="control-btn close" title="Закрыть" @click="close">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.titlebar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: var(--bg-tertiary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
|
||||
.titlebar-drag {
|
||||
flex: 1;
|
||||
padding-left: 12px;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.titlebar-controls {
|
||||
display: flex;
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
.control-btn {
|
||||
width: 46px;
|
||||
height: var(--titlebar-height);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
transition: background var(--transition-fast), color var(--transition-fast);
|
||||
}
|
||||
|
||||
.control-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.control-btn.close:hover {
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
}
|
||||
</style>
|
||||
403
src/renderer/src/components/messages/MessageList.vue
Normal file
403
src/renderer/src/components/messages/MessageList.vue
Normal file
|
|
@ -0,0 +1,403 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { useMessagesStore } from '../../stores/messages.store'
|
||||
import { useFoldersStore } from '../../stores/folders.store'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import { useSettingsStore, type SwipeAction } from '../../stores/settings.store'
|
||||
import MessageListItem from './MessageListItem.vue'
|
||||
|
||||
const messagesStore = useMessagesStore()
|
||||
const foldersStore = useFoldersStore()
|
||||
const accountsStore = useAccountsStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
const selectMode = ref(false)
|
||||
|
||||
const folderName = computed(() => foldersStore.activeFolder?.name ?? '')
|
||||
const hasSelected = computed(() => messagesStore.selectedIds.size > 0)
|
||||
const allVisibleSelected = computed(() =>
|
||||
messagesStore.filteredMessages.length > 0 &&
|
||||
messagesStore.filteredMessages.every((m) => messagesStore.selectedIds.has(m.id))
|
||||
)
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
||||
}
|
||||
|
||||
function onScroll(event: Event): void {
|
||||
const el = event.target as HTMLElement
|
||||
if (el.scrollHeight - el.scrollTop - el.clientHeight < 200) {
|
||||
messagesStore.loadMore()
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSelectAll(): void {
|
||||
if (allVisibleSelected.value) {
|
||||
messagesStore.clearSelected()
|
||||
} else {
|
||||
messagesStore.selectAll()
|
||||
}
|
||||
}
|
||||
|
||||
function exitSelectMode(): void {
|
||||
selectMode.value = false
|
||||
messagesStore.clearSelected()
|
||||
}
|
||||
|
||||
async function handleSwipeAction(action: SwipeAction, messageId: string): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
if (action === 'delete') {
|
||||
await messagesStore.deleteOne(messageId)
|
||||
} else if (action === 'toggleRead') {
|
||||
await messagesStore.toggleRead(messageId)
|
||||
} else if (action === 'toggleFlag') {
|
||||
await messagesStore.toggleFlag(messageId)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="message-list-container">
|
||||
<!-- Заголовок -->
|
||||
<div class="message-list-header">
|
||||
<h2 class="folder-title truncate">{{ folderName }}</h2>
|
||||
<button
|
||||
v-if="messagesStore.totalCount > 0"
|
||||
class="message-count"
|
||||
:class="{ 'unread-active': messagesStore.unreadOnly }"
|
||||
title="Только непрочитанные"
|
||||
@click="messagesStore.unreadOnly = !messagesStore.unreadOnly"
|
||||
>
|
||||
{{ messagesStore.totalCount }}
|
||||
</button>
|
||||
<div class="header-actions">
|
||||
<button
|
||||
class="icon-btn select-mode-btn"
|
||||
:class="{ active: selectMode }"
|
||||
title="Режим выбора"
|
||||
@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>
|
||||
<button
|
||||
class="icon-btn"
|
||||
:class="{ spinning: messagesStore.loading }"
|
||||
:disabled="messagesStore.loading"
|
||||
title="Обновить"
|
||||
@click="refresh"
|
||||
>
|
||||
↻
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Панель действий при мультивыборе -->
|
||||
<div v-if="selectMode && hasSelected" class="bulk-actions">
|
||||
<span class="bulk-count">Выбрано: {{ messagesStore.selectedIds.size }}</span>
|
||||
<button class="bulk-btn" @click="messagesStore.markSelectedAsRead()">
|
||||
✓ Прочитать
|
||||
</button>
|
||||
<button class="bulk-btn" @click="messagesStore.flagSelected()">
|
||||
⚑ Флажок
|
||||
</button>
|
||||
<button class="bulk-btn danger" @click="messagesStore.deleteSelected()">
|
||||
🗑 Удалить
|
||||
</button>
|
||||
<button class="bulk-btn" @click="exitSelectMode">Отмена</button>
|
||||
</div>
|
||||
|
||||
<!-- Загрузка -->
|
||||
<div
|
||||
v-if="messagesStore.loading && messagesStore.messages.length === 0"
|
||||
class="loading-state"
|
||||
>
|
||||
<div class="spinner" />
|
||||
<span>Загрузка писем...</span>
|
||||
</div>
|
||||
|
||||
<!-- Нет выбранной папки -->
|
||||
<div v-else-if="!foldersStore.activeFolderId" class="empty-state">
|
||||
<span>Выберите папку</span>
|
||||
</div>
|
||||
|
||||
<!-- Папка пуста -->
|
||||
<div v-else-if="messagesStore.filteredMessages.length === 0" class="empty-state">
|
||||
<span>{{ messagesStore.unreadOnly ? 'Нет непрочитанных писем' : 'В папке нет писем' }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Список писем -->
|
||||
<div v-else class="message-list" @scroll="onScroll">
|
||||
<!-- Строка "выбрать все" — только в режиме выбора -->
|
||||
<div v-if="selectMode" class="select-all-row" @click="toggleSelectAll">
|
||||
<span
|
||||
class="select-all-circle"
|
||||
:class="{ checked: allVisibleSelected, indeterminate: hasSelected && !allVisibleSelected }"
|
||||
>
|
||||
<svg v-if="allVisibleSelected" viewBox="0 0 16 16" width="10" height="10" fill="none">
|
||||
<polyline points="3,8 6.5,12 13,4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<span v-else-if="hasSelected && !allVisibleSelected" class="indeterminate-dash" />
|
||||
</span>
|
||||
<span class="select-all-text">Выбрать все</span>
|
||||
</div>
|
||||
|
||||
<MessageListItem
|
||||
v-for="message in messagesStore.filteredMessages"
|
||||
:key="message.id"
|
||||
:message="message"
|
||||
:selected="messagesStore.selectedMessageId === message.id"
|
||||
:checked="messagesStore.selectedIds.has(message.id)"
|
||||
:select-mode="selectMode"
|
||||
:swipe-left-action="settingsStore.swipeLeftAction"
|
||||
:swipe-right-action="settingsStore.swipeRightAction"
|
||||
@click="messagesStore.selectMessage(message.id)"
|
||||
@toggle-select="messagesStore.toggleSelect(message.id)"
|
||||
@swipe-action="(action) => handleSwipeAction(action, message.id)"
|
||||
/>
|
||||
|
||||
<div v-if="messagesStore.loading" class="loading-more">
|
||||
<div class="spinner-sm" /> Загрузка...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.message-list-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.message-list-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.folder-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.message-count {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
background: var(--danger);
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition: background 0.12s ease, box-shadow 0.12s ease;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
.message-count:hover {
|
||||
background: #e03a3a;
|
||||
}
|
||||
.message-count.unread-active {
|
||||
background: #a81c1c;
|
||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
color: var(--text-muted);
|
||||
border-radius: var(--radius-sm);
|
||||
transition: background var(--transition-fast), color var(--transition-fast);
|
||||
}
|
||||
|
||||
.icon-btn:hover:not(:disabled) {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.icon-btn.active {
|
||||
color: var(--accent);
|
||||
background: var(--accent-muted);
|
||||
}
|
||||
|
||||
.icon-btn:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.icon-btn.spinning {
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
/* Select mode button with custom checkbox icon */
|
||||
.select-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid currentColor;
|
||||
transition: background 0.15s ease, border-color 0.15s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.select-icon.checked {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Панель мультивыбора */
|
||||
.bulk-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 10px;
|
||||
background: var(--bg-tertiary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bulk-count {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.bulk-btn {
|
||||
font-size: 11px;
|
||||
padding: 3px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
.bulk-btn:hover {
|
||||
background: var(--border-light);
|
||||
}
|
||||
|
||||
.bulk-btn.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.bulk-btn.danger:hover {
|
||||
background: rgba(244, 71, 71, 0.15);
|
||||
}
|
||||
|
||||
/* Строка "выбрать все" */
|
||||
.select-all-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 10px 6px 5px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-tertiary);
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
.select-all-row:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.select-all-circle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
transition: background 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
.select-all-circle.checked {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.select-all-circle.indeterminate {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.indeterminate-dash {
|
||||
width: 8px;
|
||||
height: 2px;
|
||||
background: #fff;
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
.select-all-text {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.message-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.loading-state,
|
||||
.empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 2px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.loading-more {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.spinner-sm {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
415
src/renderer/src/components/messages/MessageListItem.vue
Normal file
415
src/renderer/src/components/messages/MessageListItem.vue
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||
import type { MessageEnvelope } from '@shared/types/message'
|
||||
import { formatMessageDate } from '../../utils/date'
|
||||
import { SWIPE_ACTION_INFO, type SwipeAction } from '../../stores/settings.store'
|
||||
|
||||
const props = defineProps<{
|
||||
message: MessageEnvelope
|
||||
selected: boolean
|
||||
checked: boolean
|
||||
selectMode: boolean
|
||||
swipeLeftAction: SwipeAction
|
||||
swipeRightAction: SwipeAction
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
click: []
|
||||
toggleSelect: []
|
||||
swipeAction: [action: SwipeAction]
|
||||
}>()
|
||||
|
||||
const isUnread = computed(() => !props.message.flags.seen)
|
||||
const isFlagged = computed(() => props.message.flags.flagged)
|
||||
const senderDisplay = computed(() =>
|
||||
props.message.from.name || props.message.from.email || 'Неизвестно'
|
||||
)
|
||||
const dateDisplay = computed(() => formatMessageDate(props.message.date))
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Constants
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
const CLICK_DIST = 6 // px — max displacement to count as a tap/click
|
||||
const MIN_DRAG = 12 // px horizontal before we start the visual swipe
|
||||
const TRIGGER = 90 // px visual offset → action fires
|
||||
const FLICK_SPEED = 14 // last-event deltaX that counts as a "flick"
|
||||
const FLICK_RATIO = 0.55 // flick trigger = TRIGGER * FLICK_RATIO
|
||||
const DEAD_ZONE = 28 // px accumulated deltaX before item starts moving
|
||||
const SCALE = 0.50 // visual px per accumulated deltaX past dead zone
|
||||
const RUBBER_PEAK = 72 // visual px where rubber-band starts
|
||||
const RUBBER_K = 0.12 // fraction of excess applied past rubber peak
|
||||
const IDLE_MS = 130 // ms of wheel silence → gesture over
|
||||
const H_RATIO = 2.0 // deltaX must be ≥ deltaY × H_RATIO to start gesture
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Reactive / template state
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
const wrapperRef = ref<HTMLElement>()
|
||||
const swipeOffset = ref(0)
|
||||
const isSnapping = ref(false)
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Shared visual helpers
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
const progress = computed(() => Math.min(1, Math.abs(swipeOffset.value) / TRIGGER))
|
||||
const showLeftBg = computed(() => swipeOffset.value > 0 && props.swipeRightAction !== 'none')
|
||||
const showRightBg = computed(() => swipeOffset.value < 0 && props.swipeLeftAction !== 'none')
|
||||
const leftColor = computed(() => SWIPE_ACTION_INFO[props.swipeRightAction].color)
|
||||
const rightColor = computed(() => SWIPE_ACTION_INFO[props.swipeLeftAction].color)
|
||||
const leftIcon = computed(() => SWIPE_ACTION_INFO[props.swipeRightAction].icon)
|
||||
const rightIcon = computed(() => SWIPE_ACTION_INFO[props.swipeLeftAction].icon)
|
||||
const confirmed = computed(() => Math.abs(swipeOffset.value) >= TRIGGER)
|
||||
|
||||
function applyRubberBand(v: number): number {
|
||||
const abs = Math.abs(v)
|
||||
if (abs <= RUBBER_PEAK) return v
|
||||
return Math.sign(v) * (RUBBER_PEAK + (abs - RUBBER_PEAK) * RUBBER_K)
|
||||
}
|
||||
|
||||
function fireAction(action: SwipeAction): void {
|
||||
emit('swipeAction', action)
|
||||
}
|
||||
|
||||
function snapBack(): void {
|
||||
isSnapping.value = true
|
||||
swipeOffset.value = 0
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Pointer events (mouse drag + click detection)
|
||||
//
|
||||
// KEY INSIGHT: setPointerCapture routes pointerup back to this
|
||||
// element even when the mouse leaves. This means the browser's
|
||||
// own click-event logic sees a move and may skip firing click.
|
||||
// Solution: own click detection via displacement in onPointerUp.
|
||||
// No @click handler needed — we emit('click') ourselves.
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
let ptrDown = false
|
||||
let ptrDragging = false
|
||||
let startX = 0
|
||||
let startY = 0
|
||||
|
||||
function onPointerDown(e: PointerEvent): void {
|
||||
if (e.button !== 0) return
|
||||
ptrDown = true
|
||||
ptrDragging = false
|
||||
startX = e.clientX
|
||||
startY = e.clientY
|
||||
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent): void {
|
||||
if (!ptrDown) return
|
||||
|
||||
const dx = e.clientX - startX
|
||||
const dy = e.clientY - startY
|
||||
|
||||
if (!ptrDragging) {
|
||||
if (Math.abs(dx) < MIN_DRAG) return
|
||||
if (Math.abs(dy) > Math.abs(dx)) return // vertical — not a swipe
|
||||
ptrDragging = true
|
||||
}
|
||||
|
||||
isSnapping.value = false
|
||||
|
||||
let visual = dx
|
||||
if (visual < 0 && props.swipeLeftAction === 'none') visual = 0
|
||||
if (visual > 0 && props.swipeRightAction === 'none') visual = 0
|
||||
|
||||
swipeOffset.value = applyRubberBand(visual)
|
||||
}
|
||||
|
||||
function onPointerUp(e: PointerEvent): void {
|
||||
if (!ptrDown) return
|
||||
ptrDown = false
|
||||
|
||||
const dist = Math.hypot(e.clientX - startX, e.clientY - startY)
|
||||
const wasDragging = ptrDragging
|
||||
ptrDragging = false
|
||||
|
||||
// ── Tap / click ─────────────────────────────────────────────
|
||||
// Treat as click if the pointer barely moved AND wasn't dragging.
|
||||
if (dist <= CLICK_DIST && !wasDragging) {
|
||||
snapBack()
|
||||
// Skip if click landed on the checkbox
|
||||
const target = e.target as HTMLElement
|
||||
if (!target.closest('.checkbox-col')) {
|
||||
emit('click')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ── Swipe / drag ────────────────────────────────────────────
|
||||
if (!wasDragging) {
|
||||
snapBack()
|
||||
return
|
||||
}
|
||||
|
||||
const visual = swipeOffset.value
|
||||
snapBack()
|
||||
|
||||
if (Math.abs(visual) >= TRIGGER) {
|
||||
if (visual < 0 && props.swipeLeftAction !== 'none') fireAction(props.swipeLeftAction)
|
||||
if (visual > 0 && props.swipeRightAction !== 'none') fireAction(props.swipeRightAction)
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerCancel(): void {
|
||||
ptrDown = false
|
||||
ptrDragging = false
|
||||
snapBack()
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Wheel events (trackpad horizontal gestures)
|
||||
//
|
||||
// Accumulate deltaX into wheelAcc; derive the visual offset from
|
||||
// (accumulated - DEAD_ZONE) × SCALE so tiny vibrations during a
|
||||
// tap never cause visual movement. On gesture end (IDLE_MS of
|
||||
// silence), trigger the action if the visual offset reached TRIGGER.
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
let wheelActive = false
|
||||
let wheelAcc = 0
|
||||
let lastWheelDelta = 0
|
||||
let idleTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function handleWheel(e: WheelEvent): void {
|
||||
const adx = Math.abs(e.deltaX)
|
||||
const ady = Math.abs(e.deltaY)
|
||||
|
||||
if (!wheelActive && adx < ady * H_RATIO) return
|
||||
if (adx < 1) return
|
||||
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
wheelActive = true
|
||||
lastWheelDelta = e.deltaX
|
||||
wheelAcc += e.deltaX
|
||||
isSnapping.value = false
|
||||
|
||||
// Visual offset = (accumulated past dead zone) × scale, negated
|
||||
const pastDead = Math.max(0, Math.abs(wheelAcc) - DEAD_ZONE)
|
||||
let visual = -Math.sign(wheelAcc) * pastDead * SCALE
|
||||
|
||||
if (visual < 0 && props.swipeLeftAction === 'none') visual = 0
|
||||
if (visual > 0 && props.swipeRightAction === 'none') visual = 0
|
||||
|
||||
swipeOffset.value = applyRubberBand(visual)
|
||||
|
||||
if (idleTimer !== null) clearTimeout(idleTimer)
|
||||
idleTimer = setTimeout(commitWheel, IDLE_MS)
|
||||
}
|
||||
|
||||
function commitWheel(): void {
|
||||
idleTimer = null
|
||||
wheelActive = false
|
||||
|
||||
const visual = swipeOffset.value
|
||||
const isFlick = Math.abs(lastWheelDelta) >= FLICK_SPEED
|
||||
const thresh = isFlick ? TRIGGER * FLICK_RATIO : TRIGGER
|
||||
|
||||
wheelAcc = 0
|
||||
lastWheelDelta = 0
|
||||
snapBack()
|
||||
|
||||
if (Math.abs(visual) < thresh) return
|
||||
|
||||
if (visual < 0 && props.swipeLeftAction !== 'none') fireAction(props.swipeLeftAction)
|
||||
if (visual > 0 && props.swipeRightAction !== 'none') fireAction(props.swipeRightAction)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
wrapperRef.value?.addEventListener('wheel', handleWheel, { passive: false })
|
||||
})
|
||||
onUnmounted(() => {
|
||||
wrapperRef.value?.removeEventListener('wheel', handleWheel)
|
||||
if (idleTimer !== null) clearTimeout(idleTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="wrapperRef" class="swipe-wrapper">
|
||||
|
||||
<!-- Reveal: left side (swipe-right action) -->
|
||||
<div
|
||||
v-if="showLeftBg"
|
||||
class="action-bg action-left"
|
||||
:style="{ background: leftColor, opacity: progress }"
|
||||
>
|
||||
<span class="action-icon" :class="{ confirmed }">{{ leftIcon }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Reveal: right side (swipe-left action) -->
|
||||
<div
|
||||
v-if="showRightBg"
|
||||
class="action-bg action-right"
|
||||
:style="{ background: rightColor, opacity: progress }"
|
||||
>
|
||||
<span class="action-icon" :class="{ confirmed }">{{ rightIcon }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Message row — pointer handlers here, NO @click handler -->
|
||||
<div
|
||||
class="message-item"
|
||||
:class="{ selected, unread: isUnread, checked }"
|
||||
:style="{
|
||||
transform: `translateX(${swipeOffset}px)`,
|
||||
transition: isSnapping
|
||||
? 'transform 0.22s cubic-bezier(0.22, 1, 0.36, 1)'
|
||||
: 'none'
|
||||
}"
|
||||
@pointerdown="onPointerDown"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointercancel="onPointerCancel"
|
||||
>
|
||||
<!-- Left column: custom circle checkbox (selectMode) or unread dot -->
|
||||
<div
|
||||
class="left-col"
|
||||
@pointerdown.stop
|
||||
@click.stop="selectMode && emit('toggleSelect')"
|
||||
>
|
||||
<span v-if="selectMode" class="circle-check" :class="{ 'is-checked': checked }">
|
||||
<svg v-if="checked" viewBox="0 0 16 16" width="10" height="10" fill="none">
|
||||
<polyline points="3,8 6.5,12 13,4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span v-else-if="isUnread" class="unread-dot" />
|
||||
</div>
|
||||
|
||||
<div class="message-content">
|
||||
<div class="message-top">
|
||||
<span class="sender truncate" :class="{ 'font-bold': isUnread }">
|
||||
{{ senderDisplay }}
|
||||
</span>
|
||||
<span class="date">{{ dateDisplay }}</span>
|
||||
</div>
|
||||
<div class="subject truncate" :class="{ 'font-bold': isUnread }">
|
||||
{{ message.subject }}
|
||||
</div>
|
||||
<div class="snippet truncate">{{ message.snippet }}</div>
|
||||
</div>
|
||||
|
||||
<div class="message-indicators">
|
||||
<span v-if="isFlagged" class="flag-icon">⚑</span>
|
||||
<span v-if="message.hasAttachments" class="attachment-icon">📎</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.swipe-wrapper {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.action-bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.action-left { justify-content: flex-start; padding-left: 18px; }
|
||||
.action-right { justify-content: flex-end; padding-right: 18px; }
|
||||
|
||||
.action-icon { font-size: 17px; transition: transform 0.15s ease; }
|
||||
.action-icon.confirmed { transform: scale(1.3); }
|
||||
|
||||
.message-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
width: 100%;
|
||||
padding: 10px 8px 10px 4px;
|
||||
gap: 6px;
|
||||
background: var(--bg-secondary);
|
||||
cursor: pointer;
|
||||
will-change: transform;
|
||||
touch-action: pan-y;
|
||||
user-select: none;
|
||||
transition: background 0.1s ease;
|
||||
}
|
||||
.message-item:hover { background: var(--bg-hover); }
|
||||
.message-item.selected {
|
||||
background: var(--bg-selected);
|
||||
border-left: 2px solid var(--accent);
|
||||
padding-left: 2px;
|
||||
}
|
||||
.message-item.checked {
|
||||
background: color-mix(in srgb, var(--accent) 12%, var(--bg-secondary));
|
||||
}
|
||||
.message-item.checked:hover {
|
||||
background: color-mix(in srgb, var(--accent) 18%, var(--bg-secondary));
|
||||
}
|
||||
|
||||
/* Left column: holds either circle-check or unread-dot */
|
||||
.left-col {
|
||||
width: 20px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
/* Custom circle checkbox */
|
||||
.circle-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--text-muted);
|
||||
background: transparent;
|
||||
flex-shrink: 0;
|
||||
transition: background 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
|
||||
cursor: pointer;
|
||||
}
|
||||
.circle-check:hover {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 15%, transparent);
|
||||
}
|
||||
.circle-check.is-checked {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 20%, transparent);
|
||||
}
|
||||
|
||||
.unread-dot {
|
||||
display: block;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.message-content {
|
||||
flex: 1; min-width: 0;
|
||||
display: flex; flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.message-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.sender { font-size: 13px; flex: 1; min-width: 0; }
|
||||
.font-bold { font-weight: 600; color: var(--text-primary); }
|
||||
.date { font-size: 11px; color: var(--text-muted); flex-shrink: 0; white-space: nowrap; }
|
||||
.subject { font-size: 12px; color: var(--text-secondary); }
|
||||
.snippet { font-size: 11px; color: var(--text-muted); }
|
||||
|
||||
.message-indicators {
|
||||
display: flex; flex-direction: column;
|
||||
align-items: center; gap: 4px;
|
||||
flex-shrink: 0; padding-top: 2px;
|
||||
}
|
||||
.flag-icon { font-size: 12px; color: var(--warning); }
|
||||
.attachment-icon { font-size: 12px; color: var(--text-muted); }
|
||||
</style>
|
||||
126
src/renderer/src/components/preview/MessageBody.vue
Normal file
126
src/renderer/src/components/preview/MessageBody.vue
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted, watch } from 'vue'
|
||||
import type { MessageBody } from '@shared/types/message'
|
||||
|
||||
const props = defineProps<{
|
||||
body: MessageBody
|
||||
}>()
|
||||
|
||||
const iframeRef = ref<HTMLIFrameElement | null>(null)
|
||||
|
||||
const processedHtml = computed(() => {
|
||||
if (!props.body.html) return null
|
||||
|
||||
let html = props.body.html
|
||||
|
||||
// Replace CID references with base64 data URLs
|
||||
for (const img of props.body.inlineImages) {
|
||||
html = html.replaceAll(
|
||||
`cid:${img.cid}`,
|
||||
`data:${img.contentType};base64,${img.data}`
|
||||
)
|
||||
}
|
||||
|
||||
// Wrap in a dark-themed document
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body {
|
||||
background: #1e1e1e;
|
||||
color: #e0e0e0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
padding: 16px;
|
||||
margin: 0;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
a { color: #a8e600; }
|
||||
img { max-width: 100%; height: auto; }
|
||||
table { max-width: 100%; }
|
||||
pre, code { background: #2d2d30; padding: 2px 6px; border-radius: 3px; }
|
||||
blockquote {
|
||||
border-left: 3px solid #3e3e42;
|
||||
margin: 8px 0;
|
||||
padding: 4px 12px;
|
||||
color: #a0a0a0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>${html}</body>
|
||||
</html>`
|
||||
})
|
||||
|
||||
const plainTextHtml = computed(() => {
|
||||
if (!props.body.text) return null
|
||||
const escaped = props.body.text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/\n/g, '<br>')
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body {
|
||||
background: #1e1e1e;
|
||||
color: #e0e0e0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
padding: 16px;
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
a { color: #a8e600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>${escaped}</body>
|
||||
</html>`
|
||||
})
|
||||
|
||||
const srcdoc = computed(() => processedHtml.value ?? plainTextHtml.value ?? '')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="message-body">
|
||||
<iframe
|
||||
v-if="srcdoc"
|
||||
ref="iframeRef"
|
||||
:srcdoc="srcdoc"
|
||||
sandbox="allow-same-origin"
|
||||
class="body-frame"
|
||||
/>
|
||||
<div v-else class="no-body">
|
||||
<span>Содержимое письма недоступно</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.message-body {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.body-frame {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.no-body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
</style>
|
||||
113
src/renderer/src/components/preview/MessageHeader.vue
Normal file
113
src/renderer/src/components/preview/MessageHeader.vue
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { MessageEnvelope } from '@shared/types/message'
|
||||
import { formatFullDate } from '../../utils/date'
|
||||
|
||||
const props = defineProps<{
|
||||
message: MessageEnvelope
|
||||
}>()
|
||||
|
||||
const fromDisplay = computed(() => {
|
||||
const f = props.message.from
|
||||
return f.name ? `${f.name} <${f.email}>` : f.email
|
||||
})
|
||||
|
||||
const toDisplay = computed(() =>
|
||||
props.message.to.map((a) => a.name || a.email).join(', ')
|
||||
)
|
||||
|
||||
const ccDisplay = computed(() =>
|
||||
props.message.cc.map((a) => a.name || a.email).join(', ')
|
||||
)
|
||||
|
||||
const dateDisplay = computed(() => formatFullDate(props.message.date))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="message-header">
|
||||
<h2 class="subject">{{ message.subject }}</h2>
|
||||
<div class="header-details">
|
||||
<div class="header-row">
|
||||
<span class="label">От:</span>
|
||||
<span class="value">{{ fromDisplay }}</span>
|
||||
</div>
|
||||
<div class="header-row">
|
||||
<span class="label">Кому:</span>
|
||||
<span class="value">{{ toDisplay }}</span>
|
||||
</div>
|
||||
<div v-if="ccDisplay" class="header-row">
|
||||
<span class="label">Копия:</span>
|
||||
<span class="value">{{ ccDisplay }}</span>
|
||||
</div>
|
||||
<div class="header-row">
|
||||
<span class="label">Дата:</span>
|
||||
<span class="value">{{ dateDisplay }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-badges">
|
||||
<span v-if="message.hasAttachments" class="badge">
|
||||
📎 Вложения
|
||||
</span>
|
||||
<span v-if="message.flags.flagged" class="badge flagged">
|
||||
⚑ Отмечено
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.message-header {
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.subject {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.header-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.header-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.label {
|
||||
color: var(--text-muted);
|
||||
min-width: 40px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: var(--text-secondary);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.header-badges {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.badge.flagged {
|
||||
color: var(--warning);
|
||||
background: rgba(204, 167, 0, 0.15);
|
||||
}
|
||||
</style>
|
||||
81
src/renderer/src/components/preview/MessagePreview.vue
Normal file
81
src/renderer/src/components/preview/MessagePreview.vue
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useMessagesStore } from '../../stores/messages.store'
|
||||
import MessageHeader from './MessageHeader.vue'
|
||||
import MessageBody from './MessageBody.vue'
|
||||
|
||||
const messagesStore = useMessagesStore()
|
||||
|
||||
const selectedMessage = computed(() =>
|
||||
messagesStore.messages.find((m) => m.id === messagesStore.selectedMessageId) ?? null
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="message-preview">
|
||||
<div v-if="!selectedMessage" class="no-selection">
|
||||
<div class="no-selection-icon">✉</div>
|
||||
<span>Выберите письмо для чтения</span>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<MessageHeader :message="selectedMessage" />
|
||||
|
||||
<div v-if="messagesStore.loadingBody" class="loading-body">
|
||||
<div class="spinner" />
|
||||
<span>Загрузка письма...</span>
|
||||
</div>
|
||||
|
||||
<MessageBody
|
||||
v-else-if="messagesStore.messageBody"
|
||||
:body="messagesStore.messageBody"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.message-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.no-selection {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.no-selection-icon {
|
||||
font-size: 48px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.loading-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 2px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
124
src/renderer/src/components/sidebar/AccountSwitcher.vue
Normal file
124
src/renderer/src/components/sidebar/AccountSwitcher.vue
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
<script setup lang="ts">
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const emit = defineEmits<{
|
||||
addAccount: []
|
||||
}>()
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
const router = useRouter()
|
||||
|
||||
function getInitial(email: string): string {
|
||||
return email.charAt(0).toUpperCase()
|
||||
}
|
||||
|
||||
function getAccountColor(index: number): string {
|
||||
const colors = ['#a8e600', '#00b4d8', '#e6a800', '#e066ff', '#ff6b6b', '#4ecdc4']
|
||||
return colors[index % colors.length]
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="account-switcher">
|
||||
<button
|
||||
v-for="(account, index) in accountsStore.accounts"
|
||||
:key="account.id"
|
||||
class="account-btn"
|
||||
:class="{ active: accountsStore.activeAccountId === account.id }"
|
||||
:title="account.email"
|
||||
@click="accountsStore.setActive(account.id)"
|
||||
>
|
||||
<span
|
||||
class="account-avatar"
|
||||
:style="{ background: account.color ?? getAccountColor(index) }"
|
||||
>
|
||||
{{ getInitial(account.email) }}
|
||||
</span>
|
||||
<span v-if="accountsStore.activeAccountId === account.id" class="active-indicator" />
|
||||
</button>
|
||||
|
||||
<div class="spacer" />
|
||||
|
||||
<button class="account-btn add-btn" title="Добавить аккаунт" @click="emit('addAccount')">
|
||||
<span class="add-icon">+</span>
|
||||
</button>
|
||||
|
||||
<button class="account-btn settings-btn" title="Настройки" @click="router.push('/settings')">
|
||||
<span class="settings-icon">⚙</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.account-switcher {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 8px 0;
|
||||
gap: 4px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.account-btn {
|
||||
position: relative;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-md);
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
|
||||
.account-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.account-btn.active {
|
||||
background: var(--bg-selected);
|
||||
}
|
||||
|
||||
.account-avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--radius-sm);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #1e1e1e;
|
||||
}
|
||||
|
||||
.active-indicator {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 3px;
|
||||
height: 20px;
|
||||
background: var(--accent);
|
||||
border-radius: 0 2px 2px 0;
|
||||
}
|
||||
|
||||
.add-icon {
|
||||
font-size: 18px;
|
||||
color: var(--text-muted);
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
.settings-icon {
|
||||
font-size: 16px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.add-btn:hover .add-icon,
|
||||
.settings-btn:hover .settings-icon {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
</style>
|
||||
56
src/renderer/src/components/sidebar/FolderTree.vue
Normal file
56
src/renderer/src/components/sidebar/FolderTree.vue
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
<script setup lang="ts">
|
||||
import { useFoldersStore } from '../../stores/folders.store'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import FolderTreeItem from './FolderTreeItem.vue'
|
||||
|
||||
const foldersStore = useFoldersStore()
|
||||
const accountsStore = useAccountsStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="folder-tree">
|
||||
<div v-if="accountsStore.activeAccount" class="folder-header">
|
||||
<span class="account-label truncate">{{ accountsStore.activeAccount.email }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="foldersStore.loading" class="loading">
|
||||
Загрузка папок...
|
||||
</div>
|
||||
|
||||
<div v-else-if="foldersStore.folders.length === 0 && accountsStore.activeAccount" class="empty">
|
||||
Нет папок
|
||||
</div>
|
||||
|
||||
<div v-else class="folder-list">
|
||||
<FolderTreeItem
|
||||
v-for="folder in foldersStore.folders"
|
||||
:key="folder.id"
|
||||
:folder="folder"
|
||||
:depth="0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.folder-tree {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.folder-header {
|
||||
padding: 8px 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.loading,
|
||||
.empty {
|
||||
padding: 16px 12px;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
145
src/renderer/src/components/sidebar/FolderTreeItem.vue
Normal file
145
src/renderer/src/components/sidebar/FolderTreeItem.vue
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import { useFoldersStore } from '../../stores/folders.store'
|
||||
|
||||
const props = defineProps<{
|
||||
folder: Folder
|
||||
depth: number
|
||||
}>()
|
||||
|
||||
const foldersStore = useFoldersStore()
|
||||
const expanded = ref(true)
|
||||
|
||||
const isActive = computed(() => foldersStore.activeFolderId === props.folder.id)
|
||||
const hasChildren = computed(() => props.folder.children.length > 0)
|
||||
|
||||
const folderIcon = computed(() => {
|
||||
switch (props.folder.role) {
|
||||
case SpecialFolderRole.Inbox: return '📥'
|
||||
case SpecialFolderRole.Sent: return '📤'
|
||||
case SpecialFolderRole.Drafts: return '📝'
|
||||
case SpecialFolderRole.Trash: return '🗑'
|
||||
case SpecialFolderRole.Spam: return '⚠'
|
||||
case SpecialFolderRole.Archive: return '🗃'
|
||||
default: return '📁'
|
||||
}
|
||||
})
|
||||
|
||||
function handleClick(): void {
|
||||
foldersStore.setActiveFolder(props.folder.id)
|
||||
}
|
||||
|
||||
function toggleExpand(event: Event): void {
|
||||
event.stopPropagation()
|
||||
expanded.value = !expanded.value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="folder-item-wrapper">
|
||||
<button
|
||||
class="folder-item"
|
||||
:class="{ active: isActive }"
|
||||
:style="{ paddingLeft: (depth * 16 + 8) + 'px' }"
|
||||
@click="handleClick"
|
||||
>
|
||||
<button
|
||||
v-if="hasChildren"
|
||||
class="expand-btn"
|
||||
@click="toggleExpand"
|
||||
>
|
||||
<span :class="{ rotated: expanded }">▸</span>
|
||||
</button>
|
||||
<span v-else class="expand-spacer" />
|
||||
|
||||
<span class="folder-icon" v-html="folderIcon" />
|
||||
<span class="folder-name truncate">{{ folder.name }}</span>
|
||||
<span v-if="folder.unreadCount > 0" class="unread-badge">
|
||||
{{ folder.unreadCount }}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div v-if="hasChildren && expanded" class="folder-children">
|
||||
<FolderTreeItem
|
||||
v-for="child in folder.children"
|
||||
:key="child.id"
|
||||
:folder="child"
|
||||
:depth="depth + 1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.folder-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 5px 8px;
|
||||
gap: 6px;
|
||||
border-radius: var(--radius-sm);
|
||||
margin: 0 4px;
|
||||
width: calc(100% - 8px);
|
||||
transition: background var(--transition-fast);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.folder-item:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.folder-item.active {
|
||||
background: var(--bg-selected);
|
||||
}
|
||||
|
||||
.folder-item.active .folder-name {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.expand-btn {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.expand-btn span.rotated {
|
||||
display: inline-block;
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.expand-spacer {
|
||||
width: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.folder-icon {
|
||||
font-size: 14px;
|
||||
flex-shrink: 0;
|
||||
width: 18px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.folder-name {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.unread-badge {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
padding: 1px 6px;
|
||||
border-radius: 10px;
|
||||
background: var(--danger);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
15
src/renderer/src/composables/useIpc.ts
Normal file
15
src/renderer/src/composables/useIpc.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import type { IpcChannelMap, IpcEventMap } from '@shared/types/ipc'
|
||||
|
||||
export function useIpc() {
|
||||
return {
|
||||
invoke: window.api.invoke.bind(window.api) as <K extends keyof IpcChannelMap>(
|
||||
channel: K,
|
||||
...args: IpcChannelMap[K][0] extends void ? [] : [IpcChannelMap[K][0]]
|
||||
) => Promise<IpcChannelMap[K][1]>,
|
||||
|
||||
on: window.api.on.bind(window.api) as <K extends keyof IpcEventMap>(
|
||||
channel: K,
|
||||
callback: (data: IpcEventMap[K]) => void
|
||||
) => () => void
|
||||
}
|
||||
}
|
||||
7
src/renderer/src/env.d.ts
vendored
Normal file
7
src/renderer/src/env.d.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
const component: DefineComponent<object, object, unknown>
|
||||
export default component
|
||||
}
|
||||
27
src/renderer/src/main.ts
Normal file
27
src/renderer/src/main.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import App from './App.vue'
|
||||
import './assets/styles/variables.css'
|
||||
import './assets/styles/base.css'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'mail',
|
||||
component: () => import('./views/MailView.vue')
|
||||
},
|
||||
{
|
||||
path: '/settings',
|
||||
name: 'settings',
|
||||
component: () => import('./views/SettingsView.vue')
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
87
src/renderer/src/stores/accounts.store.ts
Normal file
87
src/renderer/src/stores/accounts.store.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import { ref, computed } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import type { AccountConfig } from '@shared/types/account'
|
||||
import { useIpc } from '../composables/useIpc'
|
||||
|
||||
export const useAccountsStore = defineStore('accounts', () => {
|
||||
const { invoke, on } = useIpc()
|
||||
|
||||
const accounts = ref<AccountConfig[]>([])
|
||||
const activeAccountId = ref<string | null>(null)
|
||||
const connectionStatus = ref<Record<string, { connected: boolean; error?: string }>>({})
|
||||
const loading = ref(false)
|
||||
|
||||
const activeAccount = computed(() =>
|
||||
accounts.value.find((a) => a.id === activeAccountId.value) ?? null
|
||||
)
|
||||
|
||||
async function loadAccounts(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
accounts.value = await invoke('accounts:list')
|
||||
|
||||
// Connect all accounts first, then set active
|
||||
// (folders watcher fires on activeAccountId change — account must be connected by then)
|
||||
for (const acc of accounts.value) {
|
||||
const result = await invoke('accounts:connect', { accountId: acc.id })
|
||||
connectionStatus.value[acc.id] = {
|
||||
connected: result.success,
|
||||
error: result.error
|
||||
}
|
||||
}
|
||||
|
||||
if (accounts.value.length > 0 && !activeAccountId.value) {
|
||||
activeAccountId.value = accounts.value[0].id
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function addAccount(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
const result = await invoke('accounts:add', config)
|
||||
if (result.success) {
|
||||
await loadAccounts()
|
||||
activeAccountId.value = config.id
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function removeAccount(accountId: string): Promise<void> {
|
||||
await invoke('accounts:remove', { accountId })
|
||||
accounts.value = accounts.value.filter((a) => a.id !== accountId)
|
||||
delete connectionStatus.value[accountId]
|
||||
if (activeAccountId.value === accountId) {
|
||||
activeAccountId.value = accounts.value[0]?.id ?? null
|
||||
}
|
||||
}
|
||||
|
||||
async function testConnection(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
return invoke('accounts:test', config)
|
||||
}
|
||||
|
||||
function setActive(accountId: string): void {
|
||||
activeAccountId.value = accountId
|
||||
}
|
||||
|
||||
// Listen for status updates
|
||||
on('account:status', (data) => {
|
||||
connectionStatus.value[data.accountId] = {
|
||||
connected: data.connected,
|
||||
error: data.error
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
accounts,
|
||||
activeAccountId,
|
||||
activeAccount,
|
||||
connectionStatus,
|
||||
loading,
|
||||
loadAccounts,
|
||||
addAccount,
|
||||
removeAccount,
|
||||
testConnection,
|
||||
setActive
|
||||
}
|
||||
})
|
||||
100
src/renderer/src/stores/folders.store.ts
Normal file
100
src/renderer/src/stores/folders.store.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { ref, computed, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import { useAccountsStore } from './accounts.store'
|
||||
import { useIpc } from '../composables/useIpc'
|
||||
|
||||
export const useFoldersStore = defineStore('folders', () => {
|
||||
const { invoke } = useIpc()
|
||||
const accountsStore = useAccountsStore()
|
||||
|
||||
const foldersByAccount = ref<Record<string, Folder[]>>({})
|
||||
const activeFolderId = ref<string | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
const folders = computed(() => {
|
||||
if (!accountsStore.activeAccountId) return []
|
||||
return foldersByAccount.value[accountsStore.activeAccountId] ?? []
|
||||
})
|
||||
|
||||
const activeFolder = computed(() => {
|
||||
return findFolderById(folders.value, activeFolderId.value)
|
||||
})
|
||||
|
||||
async function loadFolders(accountId: string): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await invoke('folders:list', { accountId })
|
||||
foldersByAccount.value[accountId] = result.folders
|
||||
|
||||
// Auto-select inbox
|
||||
const inbox = findFolderByRole(result.folders, SpecialFolderRole.Inbox)
|
||||
if (inbox) {
|
||||
activeFolderId.value = inbox.id
|
||||
} else if (result.folders.length > 0) {
|
||||
activeFolderId.value = result.folders[0].id
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function setActiveFolder(folderId: string): void {
|
||||
activeFolderId.value = folderId
|
||||
}
|
||||
|
||||
// Auto-load folders when active account changes
|
||||
watch(
|
||||
() => accountsStore.activeAccountId,
|
||||
(accountId) => {
|
||||
if (accountId) {
|
||||
if (!foldersByAccount.value[accountId]) {
|
||||
loadFolders(accountId)
|
||||
} else {
|
||||
// Re-select inbox for this account
|
||||
const inbox = findFolderByRole(
|
||||
foldersByAccount.value[accountId],
|
||||
SpecialFolderRole.Inbox
|
||||
)
|
||||
if (inbox) {
|
||||
activeFolderId.value = inbox.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
foldersByAccount,
|
||||
folders,
|
||||
activeFolderId,
|
||||
activeFolder,
|
||||
loading,
|
||||
loadFolders,
|
||||
setActiveFolder
|
||||
}
|
||||
})
|
||||
|
||||
function findFolderById(folders: Folder[], id: string | null): Folder | null {
|
||||
if (!id) return null
|
||||
for (const f of folders) {
|
||||
if (f.id === id) return f
|
||||
if (f.children.length > 0) {
|
||||
const found = findFolderById(f.children, id)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function findFolderByRole(folders: Folder[], role: SpecialFolderRole): Folder | null {
|
||||
for (const f of folders) {
|
||||
if (f.role === role) return f
|
||||
if (f.children.length > 0) {
|
||||
const found = findFolderByRole(f.children, role)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
300
src/renderer/src/stores/messages.store.ts
Normal file
300
src/renderer/src/stores/messages.store.ts
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
import { ref, computed, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import type { MessageEnvelope, MessageBody } from '@shared/types/message'
|
||||
import { useAccountsStore } from './accounts.store'
|
||||
import { useFoldersStore } from './folders.store'
|
||||
import { useIpc } from '../composables/useIpc'
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
const BODY_CACHE_TTL = 3 * 60 * 60 * 1000 // 3 hours
|
||||
|
||||
interface BodyCacheEntry {
|
||||
body: MessageBody
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const bodyCache = new Map<string, BodyCacheEntry>()
|
||||
|
||||
function getCachedBody(key: string): MessageBody | null {
|
||||
const entry = bodyCache.get(key)
|
||||
if (!entry) return null
|
||||
if (Date.now() > entry.expiresAt) {
|
||||
bodyCache.delete(key)
|
||||
return null
|
||||
}
|
||||
return entry.body
|
||||
}
|
||||
|
||||
function setCachedBody(key: string, body: MessageBody): void {
|
||||
bodyCache.set(key, { body, expiresAt: Date.now() + BODY_CACHE_TTL })
|
||||
}
|
||||
|
||||
export const useMessagesStore = defineStore('messages', () => {
|
||||
const { invoke, on } = useIpc()
|
||||
const accountsStore = useAccountsStore()
|
||||
const foldersStore = useFoldersStore()
|
||||
|
||||
const messages = ref<MessageEnvelope[]>([])
|
||||
const totalCount = ref(0)
|
||||
const selectedMessageId = ref<string | null>(null)
|
||||
const messageBody = ref<MessageBody | null>(null)
|
||||
const loading = ref(false)
|
||||
const loadingBody = ref(false)
|
||||
|
||||
// Multi-select
|
||||
const selectedIds = ref<Set<string>>(new Set())
|
||||
|
||||
// Unread filter
|
||||
const unreadOnly = ref(false)
|
||||
|
||||
const filteredMessages = computed(() =>
|
||||
unreadOnly.value ? messages.value.filter((m) => !m.flags.seen) : messages.value
|
||||
)
|
||||
|
||||
async function loadMessages(accountId: string, folderId: string, offset = 0): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await invoke('messages:list', {
|
||||
accountId,
|
||||
folderId,
|
||||
offset,
|
||||
limit: PAGE_SIZE
|
||||
})
|
||||
|
||||
if (offset === 0) {
|
||||
messages.value = result.messages
|
||||
} else {
|
||||
messages.value.push(...result.messages)
|
||||
}
|
||||
totalCount.value = result.total
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
if (messages.value.length >= totalCount.value) return
|
||||
await loadMessages(
|
||||
accountsStore.activeAccountId,
|
||||
foldersStore.activeFolderId,
|
||||
messages.value.length
|
||||
)
|
||||
}
|
||||
|
||||
async function selectMessage(messageId: string): Promise<void> {
|
||||
selectedMessageId.value = messageId
|
||||
messageBody.value = null
|
||||
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
|
||||
const cacheKey = `${accountsStore.activeAccountId}:${foldersStore.activeFolderId}:${messageId}`
|
||||
const cached = getCachedBody(cacheKey)
|
||||
if (cached) {
|
||||
messageBody.value = cached
|
||||
// Still mark as read if needed
|
||||
const msg = messages.value.find((m) => m.id === messageId)
|
||||
if (msg && !msg.flags.seen) {
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: [messageId],
|
||||
flags: { seen: true }
|
||||
})
|
||||
msg.flags.seen = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
loadingBody.value = true
|
||||
try {
|
||||
const body = await invoke('messages:body', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageId
|
||||
})
|
||||
setCachedBody(cacheKey, body)
|
||||
messageBody.value = body
|
||||
|
||||
// Mark as read
|
||||
const msg = messages.value.find((m) => m.id === messageId)
|
||||
if (msg && !msg.flags.seen) {
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: [messageId],
|
||||
flags: { seen: true }
|
||||
})
|
||||
msg.flags.seen = true
|
||||
}
|
||||
} finally {
|
||||
loadingBody.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function clearSelection(): void {
|
||||
selectedMessageId.value = null
|
||||
messageBody.value = null
|
||||
}
|
||||
|
||||
// Multi-select actions
|
||||
function toggleSelect(id: string): void {
|
||||
const next = new Set(selectedIds.value)
|
||||
if (next.has(id)) {
|
||||
next.delete(id)
|
||||
} else {
|
||||
next.add(id)
|
||||
}
|
||||
selectedIds.value = next
|
||||
}
|
||||
|
||||
function selectAll(): void {
|
||||
selectedIds.value = new Set(filteredMessages.value.map((m) => m.id))
|
||||
}
|
||||
|
||||
function clearSelected(): void {
|
||||
selectedIds.value = new Set()
|
||||
}
|
||||
|
||||
async function deleteSelected(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||
const ids = [...selectedIds.value]
|
||||
await invoke('messages:delete', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: ids
|
||||
})
|
||||
messages.value = messages.value.filter((m) => !selectedIds.value.has(m.id))
|
||||
totalCount.value = Math.max(0, totalCount.value - ids.length)
|
||||
if (selectedMessageId.value && selectedIds.value.has(selectedMessageId.value)) {
|
||||
clearSelection()
|
||||
}
|
||||
selectedIds.value = new Set()
|
||||
}
|
||||
|
||||
async function deleteOne(messageId: string): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
await invoke('messages:delete', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: [messageId]
|
||||
})
|
||||
messages.value = messages.value.filter((m) => m.id !== messageId)
|
||||
totalCount.value = Math.max(0, totalCount.value - 1)
|
||||
if (selectedMessageId.value === messageId) clearSelection()
|
||||
}
|
||||
|
||||
async function toggleRead(messageId: string): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
const msg = messages.value.find((m) => m.id === messageId)
|
||||
if (!msg) return
|
||||
const newSeen = !msg.flags.seen
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: [messageId],
|
||||
flags: { seen: newSeen }
|
||||
})
|
||||
msg.flags.seen = newSeen
|
||||
}
|
||||
|
||||
async function toggleFlag(messageId: string): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
const msg = messages.value.find((m) => m.id === messageId)
|
||||
if (!msg) return
|
||||
const newFlagged = !msg.flags.flagged
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: [messageId],
|
||||
flags: { flagged: newFlagged }
|
||||
})
|
||||
msg.flags.flagged = newFlagged
|
||||
}
|
||||
|
||||
async function flagSelected(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||
const ids = [...selectedIds.value]
|
||||
// If any selected message is unflagged — flag all; otherwise unflag all
|
||||
const anyUnflagged = messages.value.some((m) => selectedIds.value.has(m.id) && !m.flags.flagged)
|
||||
const newFlagged = anyUnflagged
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: ids,
|
||||
flags: { flagged: newFlagged }
|
||||
})
|
||||
for (const msg of messages.value) {
|
||||
if (selectedIds.value.has(msg.id)) msg.flags.flagged = newFlagged
|
||||
}
|
||||
selectedIds.value = new Set()
|
||||
}
|
||||
|
||||
async function markSelectedAsRead(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||
const ids = [...selectedIds.value]
|
||||
await invoke('messages:setFlags', {
|
||||
accountId: accountsStore.activeAccountId,
|
||||
folderId: foldersStore.activeFolderId,
|
||||
messageIds: ids,
|
||||
flags: { seen: true }
|
||||
})
|
||||
for (const msg of messages.value) {
|
||||
if (selectedIds.value.has(msg.id)) {
|
||||
msg.flags.seen = true
|
||||
}
|
||||
}
|
||||
selectedIds.value = new Set()
|
||||
}
|
||||
|
||||
// Auto-load messages when folder changes
|
||||
watch(
|
||||
() => foldersStore.activeFolderId,
|
||||
(folderId) => {
|
||||
clearSelection()
|
||||
clearSelected()
|
||||
messages.value = []
|
||||
totalCount.value = 0
|
||||
unreadOnly.value = false
|
||||
if (folderId && accountsStore.activeAccountId) {
|
||||
loadMessages(accountsStore.activeAccountId, folderId)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Listen for new mail
|
||||
on('mail:new', (data) => {
|
||||
if (
|
||||
data.accountId === accountsStore.activeAccountId &&
|
||||
data.folderId === foldersStore.activeFolderId
|
||||
) {
|
||||
messages.value.unshift(data.envelope)
|
||||
totalCount.value++
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
messages,
|
||||
filteredMessages,
|
||||
totalCount,
|
||||
selectedMessageId,
|
||||
selectedIds,
|
||||
unreadOnly,
|
||||
messageBody,
|
||||
loading,
|
||||
loadingBody,
|
||||
loadMessages,
|
||||
loadMore,
|
||||
selectMessage,
|
||||
clearSelection,
|
||||
toggleSelect,
|
||||
selectAll,
|
||||
clearSelected,
|
||||
deleteSelected,
|
||||
markSelectedAsRead,
|
||||
deleteOne,
|
||||
toggleRead,
|
||||
toggleFlag,
|
||||
flagSelected
|
||||
}
|
||||
})
|
||||
44
src/renderer/src/stores/settings.store.ts
Normal file
44
src/renderer/src/stores/settings.store.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { ref, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export type SwipeAction = 'delete' | 'toggleRead' | 'toggleFlag' | 'none'
|
||||
|
||||
export const SWIPE_ACTION_LABELS: Record<SwipeAction, string> = {
|
||||
delete: 'Удалить',
|
||||
toggleRead: 'Прочитать / Непрочитанное',
|
||||
toggleFlag: 'Поставить / снять флажок',
|
||||
none: 'Нет действия'
|
||||
}
|
||||
|
||||
export const SWIPE_ACTION_INFO: Record<SwipeAction, { icon: string; color: string }> = {
|
||||
delete: { icon: '🗑', color: 'var(--danger)' },
|
||||
toggleRead: { icon: '✉', color: 'var(--accent)' },
|
||||
toggleFlag: { icon: '⚑', color: 'var(--warning)' },
|
||||
none: { icon: '', color: 'transparent' }
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'vue-mail-settings'
|
||||
|
||||
function load(): { swipeLeftAction?: SwipeAction; swipeRightAction?: SwipeAction } {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}')
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const saved = load()
|
||||
|
||||
const swipeLeftAction = ref<SwipeAction>(saved.swipeLeftAction ?? 'delete')
|
||||
const swipeRightAction = ref<SwipeAction>(saved.swipeRightAction ?? 'toggleRead')
|
||||
|
||||
watch([swipeLeftAction, swipeRightAction], () => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
||||
swipeLeftAction: swipeLeftAction.value,
|
||||
swipeRightAction: swipeRightAction.value
|
||||
}))
|
||||
})
|
||||
|
||||
return { swipeLeftAction, swipeRightAction }
|
||||
})
|
||||
24
src/renderer/src/utils/date.ts
Normal file
24
src/renderer/src/utils/date.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { formatDistanceToNow, format, isToday, isYesterday, isThisYear } from 'date-fns'
|
||||
|
||||
export function formatMessageDate(dateStr: string): string {
|
||||
const date = new Date(dateStr)
|
||||
|
||||
if (isToday(date)) {
|
||||
return format(date, 'HH:mm')
|
||||
}
|
||||
|
||||
if (isYesterday(date)) {
|
||||
return 'Yesterday'
|
||||
}
|
||||
|
||||
if (isThisYear(date)) {
|
||||
return format(date, 'MMM d')
|
||||
}
|
||||
|
||||
return format(date, 'MMM d, yyyy')
|
||||
}
|
||||
|
||||
export function formatFullDate(dateStr: string): string {
|
||||
const date = new Date(dateStr)
|
||||
return format(date, 'EEEE, MMMM d, yyyy \'at\' HH:mm')
|
||||
}
|
||||
7
src/renderer/src/views/MailView.vue
Normal file
7
src/renderer/src/views/MailView.vue
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<script setup lang="ts">
|
||||
import AppShell from '../components/layout/AppShell.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppShell />
|
||||
</template>
|
||||
232
src/renderer/src/views/SettingsView.vue
Normal file
232
src/renderer/src/views/SettingsView.vue
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
<script setup lang="ts">
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAccountsStore } from '../stores/accounts.store'
|
||||
import { useSettingsStore, SWIPE_ACTION_LABELS, type SwipeAction } from '../stores/settings.store'
|
||||
|
||||
const router = useRouter()
|
||||
const accountsStore = useAccountsStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
const swipeOptions: SwipeAction[] = ['delete', 'toggleRead', 'toggleFlag', 'none']
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="settings-view">
|
||||
<div class="settings-header">
|
||||
<button class="back-btn" @click="router.push('/')">
|
||||
← Назад
|
||||
</button>
|
||||
<h1>Настройки</h1>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<!-- Аккаунты -->
|
||||
<section>
|
||||
<h2>Аккаунты</h2>
|
||||
<div v-for="account in accountsStore.accounts" :key="account.id" class="account-item">
|
||||
<span class="account-email">{{ account.email }}</span>
|
||||
<span class="account-type">{{ account.type }}</span>
|
||||
<button class="remove-btn" @click="accountsStore.removeAccount(account.id)">
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="accountsStore.accounts.length === 0" class="empty-text">
|
||||
Нет настроенных аккаунтов
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Жесты -->
|
||||
<section>
|
||||
<h2>Жесты</h2>
|
||||
<p class="section-desc">Настройте действия при свайпе по письму</p>
|
||||
|
||||
<div class="swipe-preview">
|
||||
<div class="swipe-demo swipe-left">
|
||||
<span class="swipe-arrow">←</span>
|
||||
<span>Свайп влево</span>
|
||||
</div>
|
||||
<div class="swipe-demo swipe-right">
|
||||
<span>Свайп вправо</span>
|
||||
<span class="swipe-arrow">→</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<label class="setting-label">
|
||||
<span class="swipe-dir">← Свайп влево</span>
|
||||
</label>
|
||||
<select v-model="settingsStore.swipeLeftAction" class="setting-select">
|
||||
<option v-for="opt in swipeOptions" :key="opt" :value="opt">
|
||||
{{ SWIPE_ACTION_LABELS[opt] }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<label class="setting-label">
|
||||
<span class="swipe-dir">→ Свайп вправо</span>
|
||||
</label>
|
||||
<select v-model="settingsStore.swipeRightAction" class="setting-select">
|
||||
<option v-for="opt in swipeOptions" :key="opt" :value="opt">
|
||||
{{ SWIPE_ACTION_LABELS[opt] }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.settings-view {
|
||||
height: 100vh;
|
||||
background: var(--bg-primary);
|
||||
padding: 24px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.settings-header h1 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
padding: 6px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 32px;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.settings-content h2 {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
color: var(--text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.section-desc {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
/* Аккаунты */
|
||||
.account-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.account-email {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.account-type {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.remove-btn {
|
||||
color: var(--danger);
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.remove-btn:hover {
|
||||
background: rgba(244, 71, 71, 0.15);
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Жесты */
|
||||
.swipe-preview {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.swipe-demo {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.swipe-arrow {
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-secondary);
|
||||
margin-bottom: 8px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.setting-label {
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.swipe-dir {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.setting-select {
|
||||
background: var(--bg-input);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.setting-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
</style>
|
||||
37
src/shared/types/account.ts
Normal file
37
src/shared/types/account.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
export enum AccountType {
|
||||
IMAP = 'imap',
|
||||
Exchange = 'exchange',
|
||||
Gmail = 'gmail'
|
||||
}
|
||||
|
||||
export interface ImapCredentials {
|
||||
host: string
|
||||
port: number
|
||||
secure: boolean
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface ExchangeCredentials {
|
||||
serverUrl: string
|
||||
domain: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface GmailCredentials {
|
||||
email: string
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
export type AccountCredentials = ImapCredentials | ExchangeCredentials | GmailCredentials
|
||||
|
||||
export interface AccountConfig {
|
||||
id: string
|
||||
type: AccountType
|
||||
label: string
|
||||
email: string
|
||||
credentials: AccountCredentials
|
||||
color?: string
|
||||
}
|
||||
19
src/shared/types/folder.ts
Normal file
19
src/shared/types/folder.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
export enum SpecialFolderRole {
|
||||
Inbox = 'inbox',
|
||||
Sent = 'sent',
|
||||
Drafts = 'drafts',
|
||||
Trash = 'trash',
|
||||
Spam = 'spam',
|
||||
Archive = 'archive',
|
||||
None = 'none'
|
||||
}
|
||||
|
||||
export interface Folder {
|
||||
id: string
|
||||
name: string
|
||||
role: SpecialFolderRole
|
||||
parentId: string | null
|
||||
unreadCount: number
|
||||
totalCount: number
|
||||
children: Folder[]
|
||||
}
|
||||
5
src/shared/types/index.ts
Normal file
5
src/shared/types/index.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export * from './account'
|
||||
export * from './folder'
|
||||
export * from './message'
|
||||
export * from './provider'
|
||||
export * from './ipc'
|
||||
40
src/shared/types/ipc.ts
Normal file
40
src/shared/types/ipc.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import type { AccountConfig } from './account'
|
||||
import type { FolderListResult, MessageListResult } from './provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope } from './message'
|
||||
|
||||
export interface IpcChannelMap {
|
||||
'accounts:list': [void, AccountConfig[]]
|
||||
'accounts:add': [AccountConfig, { success: boolean; error?: string }]
|
||||
'accounts:remove': [{ accountId: string }, void]
|
||||
'accounts:test': [AccountConfig, { success: boolean; error?: string }]
|
||||
'accounts:connect': [{ accountId: string }, { success: boolean; error?: string }]
|
||||
|
||||
'folders:list': [{ accountId: string }, FolderListResult]
|
||||
|
||||
'messages:list': [
|
||||
{ accountId: string; folderId: string; offset: number; limit: number },
|
||||
MessageListResult
|
||||
]
|
||||
'messages:body': [
|
||||
{ accountId: string; folderId: string; messageId: string },
|
||||
MessageBody
|
||||
]
|
||||
'messages:setFlags': [
|
||||
{ accountId: string; folderId: string; messageIds: string[]; flags: Partial<MessageFlags> },
|
||||
void
|
||||
]
|
||||
'messages:delete': [
|
||||
{ accountId: string; folderId: string; messageIds: string[] },
|
||||
void
|
||||
]
|
||||
|
||||
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
|
||||
}
|
||||
|
||||
export interface IpcEventMap {
|
||||
'mail:new': { accountId: string; folderId: string; envelope: MessageEnvelope }
|
||||
'account:status': { accountId: string; connected: boolean; error?: string }
|
||||
}
|
||||
|
||||
export type IpcChannel = keyof IpcChannelMap
|
||||
export type IpcEvent = keyof IpcEventMap
|
||||
45
src/shared/types/message.ts
Normal file
45
src/shared/types/message.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
export interface Address {
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export interface MessageFlags {
|
||||
seen: boolean
|
||||
flagged: boolean
|
||||
answered: boolean
|
||||
deleted: boolean
|
||||
}
|
||||
|
||||
export interface MessageEnvelope {
|
||||
id: string
|
||||
folderId: string
|
||||
subject: string
|
||||
from: Address
|
||||
to: Address[]
|
||||
cc: Address[]
|
||||
date: string
|
||||
flags: MessageFlags
|
||||
hasAttachments: boolean
|
||||
snippet: string
|
||||
}
|
||||
|
||||
export interface InlineImage {
|
||||
cid: string
|
||||
contentType: string
|
||||
data: string
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
id: string
|
||||
filename: string
|
||||
contentType: string
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface MessageBody {
|
||||
id: string
|
||||
html: string | null
|
||||
text: string | null
|
||||
inlineImages: InlineImage[]
|
||||
attachments: Attachment[]
|
||||
}
|
||||
30
src/shared/types/provider.ts
Normal file
30
src/shared/types/provider.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import type { Folder } from './folder'
|
||||
import type { MessageEnvelope, MessageBody, MessageFlags } from './message'
|
||||
|
||||
export interface FolderListResult {
|
||||
folders: Folder[]
|
||||
}
|
||||
|
||||
export interface MessageListOptions {
|
||||
folderId: string
|
||||
offset: number
|
||||
limit: number
|
||||
}
|
||||
|
||||
export interface MessageListResult {
|
||||
messages: MessageEnvelope[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface IEmailProvider {
|
||||
connect(): Promise<void>
|
||||
disconnect(): Promise<void>
|
||||
isConnected(): boolean
|
||||
listFolders(): Promise<FolderListResult>
|
||||
listMessages(options: MessageListOptions): Promise<MessageListResult>
|
||||
fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody>
|
||||
updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void>
|
||||
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
|
||||
offNewMail(): void
|
||||
}
|
||||
7
tsconfig.json
Normal file
7
tsconfig.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.node.json" },
|
||||
{ "path": "./tsconfig.web.json" }
|
||||
]
|
||||
}
|
||||
26
tsconfig.node.json
Normal file
26
tsconfig.node.json
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"outDir": "./out",
|
||||
"paths": {
|
||||
"@shared/*": ["./src/shared/*"],
|
||||
"@main/*": ["./src/main/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"src/main/**/*.ts",
|
||||
"src/preload/**/*.ts",
|
||||
"src/shared/**/*.ts",
|
||||
"electron.vite.config.ts"
|
||||
]
|
||||
}
|
||||
28
tsconfig.web.json
Normal file
28
tsconfig.web.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"outDir": "./out",
|
||||
"paths": {
|
||||
"@shared/*": ["./src/shared/*"],
|
||||
"@renderer/*": ["./src/renderer/src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"src/renderer/src/**/*.ts",
|
||||
"src/renderer/src/**/*.vue",
|
||||
"src/renderer/src/**/*.d.ts",
|
||||
"src/shared/**/*.ts",
|
||||
"src/preload/index.d.ts"
|
||||
]
|
||||
}
|
||||
Loading…
Reference in a new issue