commit 649a4511651f7346ab94de5a2da2c548339c4861 Author: XIGE <710062962@qq.com> Date: Thu Nov 26 15:05:31 2026 +0800 同步插件源代码并补齐标准项目文件 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..716976f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 XIGE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2c16fe7 --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +# Mail Desk + +> 仓库:`obsidian-mail-desk` · 类型:Obsidian 插件 · 版本:`1.1.9` · 作者:XIGE + +侧边栏邮件客户端:多账户收发、定时收信、桌面提醒,支持 QQ、126 等 IMAP 邮箱。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `main.ts` +- `manifest.json` +- `src/` +- `styles.css` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..e847014 --- /dev/null +++ b/main.ts @@ -0,0 +1,609 @@ +// --------------------------------------------------------------------------- +// Mail Desk - Obsidian 侧边栏邮件客户端 +// 桌面端插件:多账户收发 / 定时收信 / 系统提醒 +// --------------------------------------------------------------------------- +import { Plugin, Notice, WorkspaceLeaf, addIcon } from "obsidian"; +import { + DEFAULT_SETTINGS, + type MailDeskSettings, + type MailSummary, +} from "./src/types"; +import { MailService } from "./src/mail-service"; +import { MailDeskSettingTab } from "./src/settings"; +import { Notifier } from "./src/notifier"; +import { MailView, VIEW_TYPE_MAIL } from "./src/view"; +import { ComposeModal } from "./src/compose"; + +addIcon("maildesk-mail", ``); + +export default class MailDeskPlugin extends Plugin { + settings!: MailDeskSettings; + mail!: MailService; + notifier!: Notifier; + ribbonIconEl: HTMLElement | null = null; + private pollTimer: number | null = null; + private saveTimer: number | null = null; + private syncing = false; + /** 打开面板前左侧栏的原始宽度,用于关闭时还原 */ + private dockSaved: { el: HTMLElement; inlineWidth: string; px: number } | null = null; + private dockTimers: number[] = []; + /** 最近一次由插件写入的宽度,用于区分「我们设的」和「你拖的」 */ + private dockAppliedPx = 0; + /** 你手动拖过侧栏:本次打开期间以你的宽度为准,不再自动加宽 */ + private dockUserPinned = false; + /** 加宽期间给右侧栏加的临时最小宽度,防止 Obsidian 的 flex 把它一起压窄 */ + private rightPin: { el: HTMLElement; prevMinWidth: string } | null = null; + + async onload(): Promise { + await this.loadSettings(); + + this.mail = new MailService(this); + this.notifier = new Notifier(this); + + // 侧边栏视图 + this.registerView(VIEW_TYPE_MAIL, (leaf) => new MailView(leaf, this)); + + // 布局就绪后修一次右栏:上一版撑宽左栏时可能把右栏压窄并写进了 workspace.json + this.app.workspace.onLayoutReady(() => { + this.repairRightDockIfSqueezed(); + if (this.mailVisibleInSidebar()) this.applyDockWidth(); + }); + + // 在侧栏标签之间切换时:邮件面板可见就加宽,切走就还原 + this.registerEvent(this.app.workspace.on("active-leaf-change", () => { + window.setTimeout(() => { + if (this.mailVisibleInSidebar()) this.applyDockWidth(); + else this.restoreDockWidth(); + }, 120); + })); + + // 你手动拖过左侧栏后,把「还原基准」更新成你拖到的宽度,关闭面板不会抹掉你的选择 + this.registerDomEvent(document, "mouseup", (ev) => { + const target = ev.target as HTMLElement | null; + const onHandle = !!target && typeof target.closest === "function" + && !!target.closest(".workspace-leaf-resize-handle"); + if (!onHandle) return; + + // 拖的是右侧栏边缘:解除临时锁宽,并把用户拖到的宽度记成「健康宽度」 + const right = this.getRightDockEl(); + if (right && right.isConnected && this.isNearRightDockEdge(ev, right)) { + this.clearRightPin(); + const rw = right.getBoundingClientRect().width; + if (rw >= 140) { + this.settings.rightDockWidth = Math.round(rw); + this.scheduleSave(); + } + return; + } + + // 只有拖「左侧栏右侧那条边」才算改左栏,避免拖右栏/主区时误判 + const saved = this.dockSaved; + if (!saved || !saved.el.isConnected) return; + if (!this.isNearLeftDockEdge(ev, saved.el)) return; + const w = saved.el.getBoundingClientRect().width; + if (w < 80) return; + if (Math.abs(w - this.dockAppliedPx) < 6) return; + saved.px = Math.round(w); + saved.inlineWidth = saved.el.style.width; + this.dockAppliedPx = Math.round(w); + this.dockUserPinned = true; + }, true); + + // 开始拖右侧栏边缘时立刻解除锁宽,否则用户拖不窄它 + this.registerDomEvent(document, "mousedown", (ev) => { + const target = ev.target as HTMLElement | null; + if (!target || typeof target.closest !== "function") return; + if (!target.closest(".workspace-leaf-resize-handle")) return; + const right = this.getRightDockEl(); + if (right && right.isConnected && this.isNearRightDockEdge(ev, right)) { + this.clearRightPin(); + } + }, true); + + // 功能区图标 + this.ribbonIconEl = this.addRibbonIcon("maildesk-mail", "Mail Desk:邮件", () => { + this.openMailView(); + }); + + // 命令 + this.addCommand({ + id: "open-mail-desk", + name: "打开邮件侧边栏", + callback: () => this.openMailView(), + }); + this.addCommand({ + id: "sync-now", + name: "立即收取新邮件", + callback: () => this.syncAll(true), + }); + this.addCommand({ + id: "compose-new", + name: "写新邮件", + callback: () => new ComposeModal(this.app, this, { kind: "new" }).open(), + }); + this.addCommand({ + id: "mark-all-read", + name: "全部标为已读", + callback: () => this.markAllRead(), + }); + this.addCommand({ + id: "open-mail-desk-center", + name: "在主区域打开邮件面板(全宽)", + callback: () => this.openMailViewInCenter(), + }); + + // 设置面板 + this.addSettingTab(new MailDeskSettingTab(this.app, this)); + + // 启动收信 + 定时轮询 + if (this.settings.syncOnStartup) { + // 延迟到界面就绪后再收,避免阻塞启动 + setTimeout(() => this.syncAll(false), 3000); + } + this.restartPolling(); + this.notifier.updateBadges(); + } + + onunload(): void { + if (this.pollTimer !== null) { + window.clearInterval(this.pollTimer); + this.pollTimer = null; + } + if (this.saveTimer !== null) { + window.clearTimeout(this.saveTimer); + this.saveTimer = null; + } + this.restoreDockWidth(); + this.notifier?.dispose(); + } + + // ---- 载入 / 保存 ---- + /** + * data.json 的影子备份路径(相对 vault 根)。 + * 背景:2026-11-18 曾发生切换库 / 重启时 loadData 读到空, + * 随后 saveSettings 把空 accounts 写回并固化,导致 4 个账号全部丢失。 + * 这里维护一份独立的 .data.backup.json:只要曾成功读到非空账号就刷新备份; + * 一旦读到空账号但备份里有,自动恢复,避免误清空被写回。 + */ + private static readonly DATA_BACKUP_PATH = ".obsidian/plugins/obsidian-mail-desk/.data.backup.json"; + + async loadSettings(): Promise { + const data = (await this.loadData()) as Partial | null; + this.settings = Object.assign({}, DEFAULT_SETTINGS, data ?? {}); + // 深合并 states + this.settings.states = data?.states ?? {}; + this.settings.accounts = data?.accounts ?? []; + + // —— 防误清空:账号为空时尝试从影子备份恢复 —— + if (this.settings.accounts.length === 0) { + try { + const adapter = this.app.vault.adapter; + const backupPath = MailDeskPlugin.DATA_BACKUP_PATH; + if (await adapter.exists(backupPath)) { + const raw = await adapter.read(backupPath); + const backup = JSON.parse(raw) as { accounts?: MailDeskSettings["accounts"] }; + if (Array.isArray(backup.accounts) && backup.accounts.length > 0) { + this.settings.accounts = backup.accounts; + console.warn(`[MailDesk] 检测到账号为空,已从影子备份恢复 ${backup.accounts.length} 个账号(data.json 读取异常)`); + new Notice(`Mail Desk:检测到账号配置异常,已自动恢复 ${backup.accounts.length} 个邮箱账户`); + // 立即写回,把误清空的状态纠正过来(覆盖可能已被写坏的主文件) + await this.saveData(this.settings); + } + } + } catch (e) { + console.error("[MailDesk] 影子备份恢复失败", e); + } + } else { + // 读到了非空账号:刷新影子备份,作为下次异常时的恢复源 + await this.refreshDataBackup(); + } + + // 布局 v3:账户栏/列表更窄、阅读区最大化。 + // 关键修复:此前 v2 迁移在用户 data.json 里标记了 layoutVersion=2,但宽度值 + // 仍是旧默认(152/340/860)——因为默认值当时没变,迁移等于空操作。 + // 这次把这些"从未真正生效的历史默认值"强制升级到 v3 新比例;真正自定义过的值保留。 + let migrated = false; + if (!this.settings.layoutVersion || this.settings.layoutVersion < 3) { + if ([152, 168, 148].includes(this.settings.sidebarWidth)) { + this.settings.sidebarWidth = DEFAULT_SETTINGS.sidebarWidth; + } + if ([340, 288].includes(this.settings.listWidth)) { + this.settings.listWidth = DEFAULT_SETTINGS.listWidth; + } + this.settings.layoutVersion = 3; + migrated = true; + } + + // v1.1.4 起本插件不再写入 Obsidian 侧栏(dock)的任何宽度, + // 清掉旧版本遗留的 autoExpandDock / dockWidth,避免残留配置误导或再次撑宽侧栏。 + const legacy = this.settings as unknown as Record; + for (const key of ["autoExpandDock", "dockWidth"]) { + if (key in legacy) { + delete legacy[key]; + migrated = true; + } + } + if (migrated) await this.saveSettings(); + } + + /** + * 刷新影子备份:仅当账号非空时写入,绝不用空账号覆盖备份。 + * 这样即使用户主动删光账号,备份仍保留最后一次的非空列表可作兜底。 + */ + private async refreshDataBackup(): Promise { + if (this.settings.accounts.length === 0) return; + try { + const adapter = this.app.vault.adapter; + const backupPath = MailDeskPlugin.DATA_BACKUP_PATH; + const payload = { accounts: this.settings.accounts }; + if (!(await adapter.exists(backupPath))) { + const dir = backupPath.slice(0, backupPath.lastIndexOf("/")); + if (!(await adapter.exists(dir))) await adapter.mkdir(dir); + } + await adapter.write(backupPath, JSON.stringify(payload, null, 2)); + } catch (e) { + console.error("[MailDesk] 影子备份写入失败", e); + } + } + + async saveSettings(): Promise { + await this.saveData(this.settings); + if (this.settings.accounts.length > 0) { + await this.refreshDataBackup(); + } else { + // 账号为空且走到这里,说明是用户在设置里主动删光了账号 → + // 清掉影子备份,避免下次启动又把这些账号恢复回来(删不掉)。 + // 注意:误清空走的是 loadSettings 里的直接 saveData,不会经过这里。 + try { + const adapter = this.app.vault.adapter; + const backupPath = MailDeskPlugin.DATA_BACKUP_PATH; + if (await adapter.exists(backupPath)) await adapter.remove(backupPath); + } catch (e) { + console.error("[MailDesk] 清理影子备份失败", e); + } + } + } + + /** 防抖保存(收信过程中频繁调用) */ + scheduleSave(): void { + if (this.saveTimer !== null) window.clearTimeout(this.saveTimer); + this.saveTimer = window.setTimeout(() => { + this.saveData(this.settings).catch((e) => console.error("[MailDesk] 保存失败", e)); + this.saveTimer = null; + }, 800); + } + + // ---- 视图 ---- + /** + * 打开邮件侧栏视图。 + * ① 侧栏折叠时展开;② reveal 视图;③ 把左侧栏临时加宽到能同时显示三栏。 + * 加宽只在「邮件面板可见」期间生效:关闭面板 / 切到别的面板 / 卸载插件都会精确还原 + * 用户原来的宽度(原来没有内联宽度就移除内联宽度,不会写死像素)。 + */ + async openMailView(): Promise { + const { workspace } = this.app; + // 侧栏折叠时先展开,否则视图藏在折叠的侧栏里,看起来像「左边栏没了」 + const split = (workspace as unknown as { + leftSplit?: { expand?: () => void; collapsed?: boolean }; + }).leftSplit; + if (split?.collapsed) { + try { split.expand?.(); } catch { /* ignore */ } + } + let leaf: WorkspaceLeaf | null = workspace.getLeavesOfType(VIEW_TYPE_MAIL) + .find((l) => !this.isLeafInMainArea(l)) ?? null; + if (!leaf) { + const newLeaf = workspace.getLeftLeaf(false); + if (!newLeaf) return; + await newLeaf.setViewState({ type: VIEW_TYPE_MAIL, active: true }); + leaf = newLeaf; + } + workspace.revealLeaf(leaf); + this.fitDockForMailView(); + } + + // ---- 侧栏宽度(回到最直接的做法:打开时写一次内联宽度,之后你随时能拖) ---- + + /** 打开面板时把左侧栏加宽到设定宽度;之后宽度完全交给你 / Obsidian 原生拖拽 */ + private getLeftDockEl(): HTMLElement | null { + const el = document.querySelector(".workspace-split.mod-left-split"); + return el instanceof HTMLElement ? el : null; + } + + private getRightDockEl(): HTMLElement | null { + const el = document.querySelector(".workspace-split.mod-right-split"); + return el instanceof HTMLElement ? el : null; + } + + /** 指针是否落在右栏左边缘(右栏的拖拽条就在这条边上) */ + private isNearRightDockEdge(ev: MouseEvent, el: HTMLElement): boolean { + const r = el.getBoundingClientRect(); + return Math.abs(ev.clientX - r.left) <= 14; + } + + /** 指针是否落在左栏右边缘(左栏的拖拽条就在这条边上) */ + private isNearLeftDockEdge(ev: MouseEvent, el: HTMLElement): boolean { + const r = el.getBoundingClientRect(); + return Math.abs(ev.clientX - r.right) <= 14; + } + + /** 右侧栏实际宽度;不存在 / 折叠时返回 0 */ + private rightDockWidth(): number { + const el = this.getRightDockEl(); + if (!el || !el.isConnected || el.getClientRects().length === 0) return 0; + return el.getBoundingClientRect().width; + } + + /** + * 右栏被挤窄时自愈。 + * 历史问题:把左栏撑得很宽时,Obsidian 的 flex 会把右栏一起压窄(200px 左右) + * 并写进 workspace.json,于是其它插件的右栏内容全部挤乱。 + * 这里在每次加宽前检查一次:正常就记录宽度,异常(<240)就恢复成记录值。 + */ + private repairRightDockIfSqueezed(): void { + const el = this.getRightDockEl(); + if (!el || !el.isConnected) return; + const w = el.getBoundingClientRect().width; + if (w <= 0) return; + const healthy = Math.max(300, Math.min(600, Math.round(this.settings.rightDockWidth || 344))); + if (w >= 240) { + if (Math.abs(w - healthy) >= 8) { + this.settings.rightDockWidth = Math.round(w); + this.scheduleSave(); + } + return; + } + // 先锁最小宽度再写宽度,否则会被 flex 立刻压回去 + this.pinRightDock(healthy); + el.style.width = `${healthy}px`; + } + + /** 加宽左栏期间锁住右栏最小宽度:只防「被压窄」,不改它自身的宽度 */ + private pinRightDock(minWidthPx?: number): void { + const el = this.getRightDockEl(); + if (!el || !el.isConnected) return; + const w = minWidthPx ?? el.getBoundingClientRect().width; + if (w <= 0) return; + if (this.rightPin && this.rightPin.el === el) { + el.style.minWidth = `${Math.round(w)}px`; + return; + } + this.clearRightPin(); + this.rightPin = { el, prevMinWidth: el.style.minWidth }; + el.style.minWidth = `${Math.round(w)}px`; + } + + /** 解除右栏临时锁宽,把侧栏交还给 Obsidian / 你的拖拽 */ + private clearRightPin(): void { + const pin = this.rightPin; + this.rightPin = null; + if (!pin || !pin.el.isConnected) return; + if (pin.prevMinWidth) pin.el.style.minWidth = pin.prevMinWidth; + else pin.el.style.removeProperty("min-width"); + } + + /** 侧栏里是否有邮件面板正在显示(主区域的邮件面板不计入) */ + mailVisibleInSidebar(): boolean { + return this.app.workspace.getLeavesOfType(VIEW_TYPE_MAIL).some((leaf) => { + if (this.isLeafInMainArea(leaf)) return false; + // 运行时有 containerEl,官方类型未声明 + const el = (leaf as unknown as { containerEl?: HTMLElement }).containerEl; + return !!el && el.isConnected && el.getClientRects().length > 0; + }); + } + + /** + * 目标宽度:设置值 → 窗口宽度 62% → (窗口 - 右栏宽度 - 主区 380px) 三者取最小。 + * 最后一项是为了「绝不靠挤压右侧栏 / 主编辑区来换宽度」。 + */ + dockTargetWidth(): number { + const wanted = Math.max(520, Math.min(1800, this.settings.dockFitWidth || 1100)); + const cap = Math.max(420, Math.floor(window.innerWidth * 0.62)); + const right = this.rightDockWidth(); + const avail = window.innerWidth - right - 380; + return Math.round(Math.max(320, Math.min(wanted, cap, avail))); + } + + /** 打开面板:立即写一次,再补两次校正(Obsidian 布局重算可能覆盖第一次) */ + fitDockForMailView(): void { + this.clearDockTimers(); + this.dockUserPinned = false; + // 先修一次右栏:之前版本把左栏撑宽时可能把右栏压窄并写进 workspace.json + this.repairRightDockIfSqueezed(); + this.applyDockWidth(); + for (const delay of [60, 240]) { + this.dockTimers.push(window.setTimeout(() => this.applyDockWidth(), delay)); + } + } + + /** 写内联宽度 —— 和 Obsidian 自己拖拽用的是同一个属性,所以之后你照样能拖 */ + private applyDockWidth(force = false): void { + if (!this.settings.dockAutoFit) return; + if (!this.mailVisibleInSidebar()) return; + const el = this.getLeftDockEl(); + if (!el) return; + if (this.dockSaved && (this.dockSaved.el !== el || !this.dockSaved.el.isConnected)) { + this.dockSaved = null; + } + if (!this.dockSaved) { + this.dockSaved = { el, inlineWidth: el.style.width, px: el.getBoundingClientRect().width }; + } + this.repairRightDockIfSqueezed(); + const target = this.dockTargetWidth(); + const cur = el.getBoundingClientRect().width; + // 只要邮件面板在侧栏里,就把右栏宽度锁住(只锁最小值),确保后续任何重排都挤不到它 + this.pinRightDock(); + if (!force && (this.dockUserPinned || cur >= target - 6)) return; + // 只写左栏宽度;右栏只临时锁最小值,宽度本身不动 + el.style.width = `${target}px`; + this.dockAppliedPx = target; + } + + /** 设置里改目标宽度:立即按新值重设 */ + retargetDockWidth(): void { + this.clearDockTimers(); + this.applyDockWidth(true); + } + + /** 还原成打开前的宽度(面板关闭 / 切到别的面板 / 卸载时) */ + restoreDockWidth(): void { + this.clearDockTimers(); + this.clearRightPin(); + this.dockUserPinned = false; + this.dockAppliedPx = 0; + const saved = this.dockSaved; + this.dockSaved = null; + if (!saved) return; + const el = saved.el; + if (!el.isConnected) return; + if (saved.inlineWidth) { + el.style.width = saved.inlineWidth; + return; + } + el.style.removeProperty("width"); + // 移除内联宽度后若塌了(没有别的宽度来源),退回记录值兜底 + const w = el.getBoundingClientRect().width; + if (w < 120) el.style.width = `${Math.round(saved.px)}px`; + } + + private clearDockTimers(): void { + for (const t of this.dockTimers) window.clearTimeout(t); + this.dockTimers = []; + } + + /** 视图关闭后判断还有没有邮件面板在显示,没有才还原 */ + handleMailViewClosed(): void { + window.setTimeout(() => { + if (!this.mailVisibleInSidebar()) this.restoreDockWidth(); + }, 300); + } + + /** 判断 leaf 是否位于主编辑区(不在左右 side dock 里) */ + private isLeafInMainArea(leaf: WorkspaceLeaf): boolean { + const ws = this.app.workspace as unknown as { + leftSplit?: unknown; + rightSplit?: unknown; + }; + let node: { parent?: unknown } | null = leaf as unknown as { parent?: unknown }; + while (node?.parent) { + const p = node.parent; + if (p === ws.leftSplit || p === ws.rightSplit) return false; + node = p as { parent?: unknown }; + } + return true; + } + + /** 在主编辑区打开邮件面板(大屏/专注阅读用,宽度充足) */ + async openMailViewInCenter(): Promise { + const { workspace } = this.app; + const existing = workspace.getLeavesOfType(VIEW_TYPE_MAIL) + .find((leaf) => this.isLeafInMainArea(leaf)); + if (existing) { + workspace.revealLeaf(existing); + return; + } + const newLeaf = workspace.getLeaf("tab"); + await newLeaf.setViewState({ type: VIEW_TYPE_MAIL, active: true }); + workspace.revealLeaf(newLeaf); + } + + refreshView(): void { + for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_MAIL)) { + const view = leaf.view; + if (view instanceof MailView) view.refresh(); + } + } + + openSettings(): void { + // 打开 Obsidian 设置并定位到插件 + const settingTabs = (this.app as unknown as { + setting: { open: () => void; openTabById: (id: string) => void }; + }).setting; + try { + settingTabs.open(); + settingTabs.openTabById("obsidian-mail-desk"); + } catch { + new Notice("请到 设置 → 第三方插件 → Mail Desk 配置"); + } + } + + // ---- 提醒 ---- + async requestNotificationPermission(): Promise { + await this.notifier?.requestPermission(); + } + + updateBadges(): void { + this.notifier?.updateBadges(); + } + + // ---- 收信 ---- + restartPolling(): void { + if (this.pollTimer !== null) { + window.clearInterval(this.pollTimer); + this.pollTimer = null; + } + const min = this.settings.pollInterval; + if (min <= 0) return; + this.pollTimer = window.setInterval(() => { + this.syncAll(false); + }, min * 60 * 1000); + } + + /** 收取所有启用账户的新邮件 */ + async syncAll(manual: boolean): Promise { + if (this.syncing) { + if (manual) new Notice("正在收信中,请稍候…"); + return; + } + const accounts = this.settings.accounts.filter((a) => a.enabled && a.secretId); + if (!accounts.length) { + if (manual) new Notice("没有可收取的账户。请先在设置中添加并配置授权码。"); + return; + } + this.syncing = true; + if (manual) new Notice("正在收取邮件…"); + + const allNew: MailSummary[] = []; + const errors: string[] = []; + for (const acc of accounts) { + try { + const mails = await this.mail.fetchNew(acc, this.settings.defaultFolder || "INBOX"); + allNew.push(...mails); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + errors.push(`${acc.name}: ${msg}`); + const st = this.settings.states[acc.id]; + if (st) st.lastError = msg; + if (this.settings.debug) console.error("[MailDesk]", acc.name, e); + } + } + + this.syncing = false; + await this.saveSettings(); + this.refreshView(); + this.updateBadges(); + + if (allNew.length) { + await this.notifier.notifyNew(allNew); + } else if (manual && !errors.length) { + new Notice("没有新邮件"); + } + if (errors.length) { + new Notice(`收信出错(${errors.length}):${errors[0].slice(0, 100)}`, 10000); + } + } + + /** 把所有缓存邮件标为已读(仅本地缓存,不改服务器) */ + private markAllRead(): void { + let count = 0; + for (const state of Object.values(this.settings.states)) { + for (const m of state?.mails ?? []) { + if (!m.seen) { m.seen = true; count++; } + } + } + if (!count) { new Notice("没有未读邮件"); return; } + this.saveSettings(); + this.refreshView(); + this.updateBadges(); + new Notice(`✓ 已将 ${count} 封邮件标为已读(仅本地)`); + } +} diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..d2ce2d2 --- /dev/null +++ b/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "obsidian-mail-desk", + "name": "Mail Desk", + "version": "1.1.9", + "minAppVersion": "1.11.4", + "description": "侧边栏邮件客户端:多账户收发、定时收信、桌面提醒。支持 QQ、126 等 IMAP 邮箱。", + "author": "XIGE", + "isDesktopOnly": true +} diff --git a/src/compose.ts b/src/compose.ts new file mode 100644 index 0000000..28f79c6 --- /dev/null +++ b/src/compose.ts @@ -0,0 +1,188 @@ +// --------------------------------------------------------------------------- +// 写信 / 回复 / 转发 弹窗 +// --------------------------------------------------------------------------- +import { App, Modal, Notice, Setting } from "obsidian"; +import type MailDeskPlugin from "../main"; +import type { MailAccount, MailDetail } from "./types"; + +export type ComposeMode = + | { kind: "new" } + | { kind: "reply"; account: MailAccount; mail: MailDetail; all: boolean } + | { kind: "forward"; account: MailAccount; mail: MailDetail }; + +export class ComposeModal extends Modal { + private to = ""; + private cc = ""; + private subject = ""; + private body = ""; + private account: MailAccount | null = null; + private files: File[] = []; + private inReplyTo?: string; + private references?: string; + private sending = false; + private sendBtn!: HTMLButtonElement; + + constructor( + app: App, + private plugin: MailDeskPlugin, + private mode: ComposeMode, + ) { + super(app); + const accounts = plugin.settings.accounts.filter((a) => a.enabled); + const first = mode.kind === "new" ? accounts[0] : mode.account; + if (!first) { + queueMicrotask(() => { + new Notice("请先添加一个启用的邮箱账户,再写邮件"); + this.close(); + }); + return; + } + this.account = first; + + if (mode.kind === "reply") { + const m = mode.mail; + this.to = m.from; + this.subject = m.subject.startsWith("Re:") ? m.subject : "Re: " + m.subject; + this.inReplyTo = m.uid + "@" + m.accountId; + this.references = this.inReplyTo; + const quoted = `\n\n---------- 原邮件 ----------\n发件人: ${m.fromName} <${m.from}>\n时间: ${new Date(m.date).toLocaleString()}\n主题: ${m.subject}\n\n${(m.text || m.html.replace(/<[^>]*>/g, " ")).slice(0, 2000)}`; + this.body = quoted; + if (mode.all && m.to) this.cc = m.to; + } else if (mode.kind === "forward") { + const m = mode.mail; + this.subject = m.subject.startsWith("Fwd:") ? m.subject : "Fwd: " + m.subject; + this.body = `\n\n---------- 转发邮件 ----------\n发件人: ${m.fromName} <${m.from}>\n时间: ${new Date(m.date).toLocaleString()}\n主题: ${m.subject}\n\n${(m.text || m.html.replace(/<[^>]*>/g, " ")).slice(0, 2000)}`; + } + } + + onOpen(): void { + if (!this.account) return; + const { contentEl } = this; + contentEl.empty(); + contentEl.addClass("maildesk-compose"); + contentEl.createEl("h2", { text: this.mode.kind === "new" ? "写邮件" : this.mode.kind === "reply" ? "回复邮件" : "转发邮件" }); + + // 新建邮件时恢复上次未发完的草稿 + if (this.mode.kind === "new") { + const draft = this.plugin.settings.draft; + if (draft) { + this.to = draft.to || ""; + this.cc = draft.cc || ""; + this.subject = draft.subject || ""; + this.body = draft.body || ""; + } + } + + new Setting(contentEl).setName("发件账户").addDropdown((d) => { + this.plugin.settings.accounts.filter((a) => a.enabled).forEach((a) => d.addOption(a.id, a.email)); + d.setValue(this.account!.id).onChange((v) => { + this.account = this.plugin.settings.accounts.find((a) => a.id === v) ?? this.account; + }); + }); + + new Setting(contentEl).setName("收件人").addText((t) => + t.setValue(this.to).setPlaceholder("多个用逗号分隔").onChange((v) => this.to = v)); + new Setting(contentEl).setName("抄送").addText((t) => + t.setValue(this.cc).setPlaceholder("可选").onChange((v) => this.cc = v)); + new Setting(contentEl).setName("主题").addText((t) => + t.setValue(this.subject).onChange((v) => this.subject = v)); + + const bodyWrap = contentEl.createDiv("maildesk-compose-body-wrap"); + const bodyEl = bodyWrap.createEl("textarea", { cls: "maildesk-compose-body" }); + bodyEl.value = this.body; + bodyEl.placeholder = "正文…"; + bodyEl.oninput = () => this.body = bodyEl.value; + + new Setting(contentEl).setName("附件").addButton((b) => b + .setButtonText("选择文件") + .onClick(() => { + const input = document.createElement("input"); + input.type = "file"; + input.multiple = true; + input.onchange = () => { + if (input.files) { + this.files.push(...Array.from(input.files)); + new Notice(`已添加 ${input.files.length} 个附件`); + this.renderAttachmentList(contentEl); + } + }; + input.click(); + })); + + this.attachmentListEl = contentEl.createDiv("maildesk-compose-attachments"); + this.renderAttachmentList(contentEl); + + const footer = contentEl.createDiv("maildesk-compose-footer"); + const cancel = footer.createEl("button", { text: "取消" }); + cancel.onclick = () => this.close(); + this.sendBtn = footer.createEl("button", { cls: "mod-cta", text: "发送" }); + this.sendBtn.onclick = () => this.send(); + } + + private attachmentListEl!: HTMLDivElement; + + private renderAttachmentList(container: HTMLElement) { + if (!this.attachmentListEl) return; + this.attachmentListEl.empty(); + this.files.forEach((f, i) => { + const row = this.attachmentListEl.createDiv("maildesk-att-row"); + row.createSpan({ text: `${f.name} (${(f.size / 1024).toFixed(0)} KB)` }); + row.createEl("button", { text: "×", cls: "maildesk-att-remove" }) + .onclick = () => { this.files.splice(i, 1); this.renderAttachmentList(container); }; + }); + } + + private async send() { + if (!this.account || this.sending) return; + if (!this.to.trim()) { new Notice("请填写收件人"); return; } + if (!this.subject.trim()) { new Notice("请填写主题"); return; } + this.sending = true; + this.sendBtn.disabled = true; + this.sendBtn.setText("发送中…"); + const body = this.body.trim(); + + try { + const attachments = await Promise.all(this.files.map(async (f) => ({ + filename: f.name, + content: Buffer.from(await f.arrayBuffer()), + contentType: f.type || "application/octet-stream", + }))); + await this.plugin.mail.send(this.account, { + to: this.to, + cc: this.cc || undefined, + subject: this.subject, + text: body, + attachments, + inReplyTo: this.inReplyTo, + references: this.references, + }); + // 发送成功,清空草稿(仅新建邮件) + if (this.mode.kind === "new") { + this.plugin.settings.draft = null; + this.plugin.saveSettings(); + } + new Notice("✓ 邮件已发送"); + this.close(); + } catch (e) { + new Notice("发送失败:" + (e instanceof Error ? e.message : String(e)), 8000); + this.sending = false; + this.sendBtn.disabled = false; + this.sendBtn.setText("发送"); + } + } + + onClose(): void { + // 关闭时若还有内容,存为草稿(仅新建邮件) + if (!this.sending && this.mode.kind === "new" && (this.to || this.subject || this.body.trim())) { + this.plugin.settings.draft = { + to: this.to, + cc: this.cc, + subject: this.subject, + body: this.body, + savedAt: Date.now(), + }; + this.plugin.saveSettings(); + } + this.contentEl.empty(); + } +} diff --git a/src/mail-service.ts b/src/mail-service.ts new file mode 100644 index 0000000..84c63fb --- /dev/null +++ b/src/mail-service.ts @@ -0,0 +1,399 @@ +// --------------------------------------------------------------------------- +// 邮件服务:基于 imapflow(收)+ nodemailer(发)+ mailparser(解析) +// 仅在桌面端可用(依赖 Node 网络库) +// --------------------------------------------------------------------------- +import { ImapFlow } from "imapflow"; +import { simpleParser } from "mailparser"; +import nodemailer from "nodemailer"; +import type { MailAccount, MailSummary, MailDetail, AttachmentInfo, AccountState } from "./types"; +import type MailDeskPlugin from "../main"; + +export interface SendPayload { + to: string; + cc?: string; + bcc?: string; + subject: string; + text?: string; + html?: string; + attachments?: { filename: string; content: Buffer; contentType?: string }[]; + inReplyTo?: string; + references?: string; +} + +export class MailService { + constructor(private plugin: MailDeskPlugin) {} + + /** 从系统密钥链取授权码。取不到返回 null。 */ + getSecret(account: MailAccount): string | null { + try { + const value = this.plugin.app.secretStorage?.getSecret(account.secretId) ?? null; + return value && value.trim() ? value.trim() : null; + } catch (e) { + this.log("读取密钥失败", e); + return null; + } + } + + private log(...args: unknown[]) { + if (this.plugin.settings.debug) console.log("[MailDesk]", ...args); + } + + /** 建立 IMAP 连接 */ + private async connect(account: MailAccount): Promise { + const pass = this.getSecret(account); + if (!pass) throw new Error("授权码未设置,请到 设置 → Mail Desk 选择密钥"); + const client = new ImapFlow({ + host: account.imapHost, + port: account.imapPort, + secure: account.secure, + auth: { user: account.email, pass }, + logger: false, + disableAutoIdle: true, + connectionTimeout: 20000, + greetingTimeout: 20000, + socketTimeout: 60000, + }); + await client.connect(); + return client; + } + + /** 测试账户连通性(IMAP + SMTP) */ + async testConnection(account: MailAccount): Promise<{ ok: boolean; error?: string }> { + let client: ImapFlow | null = null; + try { + client = await this.connect(account); + await client.list(); + await client.logout(); + client = null; + } catch (e) { + if (client) try { await client.close(); } catch { /* ignore */ } + return { ok: false, error: "IMAP: " + this.errMsg(e) }; + } + try { + const transporter = this.makeTransporter(account); + await transporter.verify(); + transporter.close(); + return { ok: true }; + } catch (e) { + return { ok: false, error: "SMTP: " + this.errMsg(e) }; + } + } + + private errMsg(e: unknown): string { + if (e instanceof Error) return e.message; + return String(e); + } + + /** 列出邮箱文件夹 */ + async listFolders(account: MailAccount): Promise { + const client = await this.connect(account); + try { + const list = await client.list(); + return list.map((f) => f.path).sort(); + } finally { + await client.logout().catch(() => {}); + } + } + + /** + * 增量收信。返回本次发现的新邮件(已完成去重)。 + * 首次同步:拉取最近 fetchDays 天建立基线,不返回为新邮件。 + */ + async fetchNew(account: MailAccount, folder = "INBOX"): Promise { + const LIMIT_FIRST = 200; // 首次基线最多缓存 200 封 + const state = this.getState(account.id); + const client = await this.connect(account); + try { + const info = await client.mailboxOpen(folder, { readOnly: false }); + this.log(`[${account.name}] ${folder} 邮件总数=${info.exists}`); + + let source: string; + if (!state.initialized) { + // 首次:用 search 按日期拿 UID 列表,构造合法序列建立基线 + const since = account.fetchDays > 0 + ? new Date(Date.now() - account.fetchDays * 86400000) + : undefined; + const uids = await client.search(since ? { since } : {}, { uid: true }); + if (!uids || !uids.length) { + state.initialized = true; + state.lastSync = Date.now(); + state.lastError = ""; + this.saveState(account.id, state); + return []; + } + const nums = uids.map(Number).sort((a, b) => a - b); + // 只保留最近的 LIMIT 封作为基线,构造 min:max 序列 + const recent = nums.slice(-LIMIT_FIRST); + source = `${recent[0]}:${recent[recent.length - 1]}`; + state.lastUid = Math.max(state.lastUid, recent[recent.length - 1]); + } else { + const start = (state.lastUid || 0) + 1; + const uidNext = Number((info as unknown as { uidNext?: number }).uidNext ?? 0); + if (uidNext > 0 && start >= uidNext) { + // 没有新邮件 + state.lastSync = Date.now(); + state.lastError = ""; + this.saveState(account.id, state); + return []; + } + source = `${start}:*`; + } + + const result: MailSummary[] = []; + let maxUid = state.lastUid; + let count = 0; + const LIMIT = 200; // 单次最多处理 200 封,防止卡死 + + for await (const msg of client.fetch(source, { + uid: true, + envelope: true, + flags: true, + internalDate: true, + bodyStructure: false, + }, { uid: true })) { + if (count++ >= LIMIT) break; + const uid = Number(msg.uid); + if (uid > maxUid) maxUid = uid; + + const env = msg.envelope; + if (!env) continue; + const from = env.from?.[0]; + const to = env.to?.[0]; + const subject = env.subject || "(无主题)"; + const date = msg.internalDate instanceof Date + ? msg.internalDate.toISOString() + : (env.date instanceof Date ? env.date.toISOString() : new Date().toISOString()); + + // 摘要在打开邮件时补全;列表阶段先用空串,避免每封都拉正文拖慢同步 + const snippet = ""; + + const summary: MailSummary = { + accountId: account.id, + folder, + uid, + subject, + from: from?.address || "", + fromName: from?.name || "", + to: to?.address || "", + date, + snippet, + seen: msg.flags?.has("\\Seen") ?? false, + hasAttachment: false, + attachmentCount: 0, + }; + result.push(summary); + } + + const wasInitialized = state.initialized; + state.lastUid = Math.max(state.lastUid, maxUid); + state.initialized = true; + state.lastSync = Date.now(); + state.lastError = ""; + + // 合并进缓存(按 account+folder+uid 去重,保留最新 300 封) + const freshKeys = new Set(result.map((m) => `${m.accountId}|${m.folder}|${m.uid}`)); + const merged = [ + ...result, + ...state.mails.filter((m) => !freshKeys.has(`${m.accountId}|${m.folder}|${m.uid}`)), + ]; + merged.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); + state.mails = merged.slice(0, 300); + this.saveState(account.id, state); + + // 首次同步不提醒 + if (!wasInitialized) return []; + return result; + } finally { + await client.logout().catch(() => {}); + } + } + + /** 读取邮件正文与附件列表,并标记为已读 */ + async getMail(account: MailAccount, folder: string, uid: number, markSeen = true): Promise { + const client = await this.connect(account); + try { + await client.mailboxOpen(folder, { readOnly: false }); + const raw = await client.fetchOne(String(uid), { source: true }, { uid: true }); + if (!raw || !raw.source) return null; + const source = Buffer.isBuffer(raw.source) ? raw.source : Buffer.from(String(raw.source)); + const parsed = await simpleParser(source, { skipHtmlToText: false, skipTextToHtml: true }); + + const attachments: AttachmentInfo[] = (parsed.attachments || []).map((a) => ({ + filename: a.filename || "attachment", + contentType: a.contentType || "application/octet-stream", + size: a.size || a.content?.length || 0, + })); + + const fromObj = Array.isArray(parsed.from) ? parsed.from[0] : parsed.from; + const toObj = Array.isArray(parsed.to) ? parsed.to[0] : parsed.to; + const fromAddr = fromObj?.value?.[0]; + const toAddr = toObj?.value?.[0]; + const state = this.getState(account.id); + const cached = state.mails.find((m) => m.accountId === account.id && m.folder === folder && m.uid === uid); + const snippet = (parsed.text || "").replace(/\s+/g, " ").trim().slice(0, 120); + + const detail: MailDetail = { + accountId: account.id, + folder, + uid, + subject: parsed.subject || cached?.subject || "(无主题)", + from: fromAddr?.address || cached?.from || "", + fromName: fromAddr?.name || cached?.fromName || "", + to: toAddr?.address || cached?.to || "", + date: (parsed.date instanceof Date ? parsed.date : new Date()).toISOString(), + snippet: snippet || cached?.snippet || "", + seen: true, + hasAttachment: attachments.length > 0, + attachmentCount: attachments.length, + html: typeof parsed.html === "string" ? parsed.html : "", + text: parsed.text || "", + attachments, + }; + + // 打开邮件时把摘要和附件信息回填到缓存,列表下次显示更完整 + if (cached) { + if (snippet) cached.snippet = snippet; + cached.hasAttachment = attachments.length > 0; + cached.attachmentCount = attachments.length; + } + + if (markSeen) { + await client.messageFlagsAdd(String(uid), ["\\Seen"], { uid: true }).catch(() => {}); + const m = state.mails.find((x) => x.accountId === account.id && x.folder === folder && x.uid === uid); + if (m) m.seen = true; + } + this.saveState(account.id, state); + return detail; + } finally { + await client.logout().catch(() => {}); + } + } + + /** 标记已读 / 未读 */ + async setSeen(account: MailAccount, folder: string, uid: number, seen: boolean): Promise { + const client = await this.connect(account); + try { + await client.mailboxOpen(folder, { readOnly: false }); + if (seen) { + await client.messageFlagsAdd(String(uid), ["\\Seen"], { uid: true }); + } else { + await client.messageFlagsRemove(String(uid), ["\\Seen"], { uid: true }); + } + const state = this.getState(account.id); + const m = state.mails.find((x) => x.accountId === account.id && x.folder === folder && x.uid === uid); + if (m) m.seen = seen; + this.saveState(account.id, state); + } finally { + await client.logout().catch(() => {}); + } + } + + /** 删除单封邮件(设置 \Deleted 并 expunge) */ + async deleteMail(account: MailAccount, folder: string, uid: number): Promise { + await this.deleteMails(account, folder, [uid]); + } + + /** + * 批量删除同一邮箱文件夹下的多封邮件:复用单个连接、一次打开邮箱、一次 expunge。 + * 返回真正删除成功的 UID 列表。失败只影响单封,不中断整批。 + */ + async deleteMails(account: MailAccount, folder: string, uids: number[]): Promise { + if (!uids.length) return []; + let deleted: number[] = []; + const client = await this.connect(account); + try { + await client.mailboxOpen(folder, { readOnly: false }); + // 一次调用删除整批 UID(imapflow 内部执行 EXPUNGE),单连接、单次往返 + const ok = await client.messageDelete(uids, { uid: true }); + deleted = ok ? [...uids] : []; + } finally { + // 与其他操作一致:无条件关闭连接,避免连接泄漏导致后续删除连不上 + await client.logout().catch(() => {}); + } + if (deleted.length) { + const state = this.getState(account.id); + const deletedSet = new Set(deleted); + state.mails = state.mails.filter( + (m) => !(m.accountId === account.id && m.folder === folder && deletedSet.has(m.uid)), + ); + this.saveState(account.id, state); + } + return deleted; + } + + /** 下载单个附件到指定路径(取完整邮件源码后用 mailparser 提取附件) */ + async downloadAttachment(account: MailAccount, folder: string, uid: number, filename: string, targetPath: string): Promise { + const { writeFile } = await import("fs/promises"); + const client = await this.connect(account); + try { + await client.mailboxOpen(folder, { readOnly: true }); + const raw = await client.fetchOne(String(uid), { source: true }, { uid: true }); + if (!raw || !raw.source) throw new Error("无法读取邮件源码"); + const source = Buffer.isBuffer(raw.source) ? raw.source : Buffer.from(String(raw.source)); + const parsed = await simpleParser(source); + const att = parsed.attachments?.find((a) => a.filename === filename); + if (!att) throw new Error("未找到附件: " + filename); + await writeFile(targetPath, att.content); + } finally { + await client.logout().catch(() => {}); + } + } + + private makeTransporter(account: MailAccount) { + const pass = this.getSecret(account); + if (!pass) throw new Error("授权码未设置,请到 设置 → Mail Desk 选择密钥"); + return nodemailer.createTransport({ + host: account.smtpHost, + port: account.smtpPort, + secure: account.smtpSecure ?? account.secure, + auth: { user: account.email, pass }, + connectionTimeout: 20000, + greetingTimeout: 20000, + socketTimeout: 60000, + // 国内邮箱偶发 TLS 握手问题,放宽证书校验 + tls: { rejectUnauthorized: false }, + }); + } + + /** 发送邮件 */ + async send(account: MailAccount, payload: SendPayload): Promise { + const transporter = this.makeTransporter(account); + try { + await transporter.sendMail({ + from: { name: account.senderName || account.name || account.email, address: account.email }, + to: payload.to, + cc: payload.cc || undefined, + bcc: payload.bcc || undefined, + subject: payload.subject, + text: payload.text || undefined, + html: payload.html || undefined, + attachments: payload.attachments?.map((a) => ({ + filename: a.filename, + content: a.content, + contentType: a.contentType, + })), + headers: payload.inReplyTo ? { + "In-Reply-To": payload.inReplyTo, + References: payload.references || payload.inReplyTo, + } : undefined, + }); + } finally { + transporter.close(); + } + } + + private getState(accountId: string): AccountState { + let s = this.plugin.settings.states[accountId]; + if (!s) { + s = { lastUid: 0, initialized: false, mails: [], lastSync: 0, lastError: "" }; + this.plugin.settings.states[accountId] = s; + } + if (!s.mails) s.mails = []; + return s; + } + + private saveState(accountId: string, state: AccountState) { + this.plugin.settings.states[accountId] = state; + this.plugin.scheduleSave(); + } +} diff --git a/src/notifier.ts b/src/notifier.ts new file mode 100644 index 0000000..706466e --- /dev/null +++ b/src/notifier.ts @@ -0,0 +1,180 @@ +// --------------------------------------------------------------------------- +// 提醒模块:系统通知 / 应用内 Notice / 侧边栏角标 / 状态栏计数 +// --------------------------------------------------------------------------- +import { Notice } from "obsidian"; +import type MailDeskPlugin from "../main"; +import type { MailSummary } from "./types"; + +export class Notifier { + private statusBarEl: HTMLElement | null = null; + private permission: NotificationPermission = "default"; + private refreshTimer: number | null = null; + /** 已提醒过的邮件幂等键:accountId|folder|uid。防止同一封邮件被重复通知 */ + private notifiedKeys = new Set(); + + constructor(private plugin: MailDeskPlugin) {} + + /** 请求系统通知权限 */ + async requestPermission(): Promise { + if (typeof Notification === "undefined") return "denied"; + try { + if (Notification.permission === "granted") { + this.permission = "granted"; + return this.permission; + } + this.permission = await Notification.requestPermission(); + return this.permission; + } catch { + return "denied"; + } + } + + getStatus(): NotificationPermission { + return this.permission; + } + + /** 邮件唯一键:账户 + 文件夹 + UID */ + private keyOf(m: MailSummary): string { + return `${m.accountId}|${m.folder}|${m.uid}`; + } + + /** + * 有新邮件时触发所有已启用的提醒渠道。 + * 去重分两层:① 已经 seen 的不提醒;② 本会话已提醒过的幂等键不重复提醒。 + * 这样即使 fetchNew 因基线重建/重复拉取返回旧邮件,也不会再次弹通知。 + */ + async notifyNew(mails: MailSummary[]): Promise { + if (!mails.length) return; + const s = this.plugin.settings; + + // 幂等过滤:已读 + 本会话已提醒过的,直接剔除 + const fresh = mails.filter((m) => { + if (m.seen) return false; + const key = this.keyOf(m); + if (this.notifiedKeys.has(key)) return false; + this.notifiedKeys.add(key); + return true; + }); + if (!fresh.length) { + this.updateBadges(); + return; + } + + // 应用内 Notice + if (s.notifyNotice) { + if (s.aggregateNotification) { + const sample = fresh[0]; + const title = fresh.length === 1 + ? `新邮件:${sample.fromName || sample.from} — ${sample.subject}` + : `${fresh.length} 封新邮件`; + new Notice(title, 6000); + } else { + for (const m of fresh.slice(0, 5)) { + new Notice(`新邮件:${m.fromName || m.from} — ${m.subject}`, 6000); + } + } + } + + // 系统桌面通知 + if (s.notifySystem && typeof Notification !== "undefined") { + const permission = await this.requestPermission(); + if (permission === "granted") { + const title = fresh.length === 1 + ? `${fresh[0].fromName || fresh[0].from}` + : `${fresh.length} 封新邮件`; + const body = fresh.length === 1 + ? fresh[0].subject + : fresh.slice(0, 3).map((m) => m.subject).join("\n"); + try { + const n = new Notification("Mail Desk · " + title, { body, silent: false }); + n.onclick = () => { + try { n.close(); } catch { /* ignore */ } + try { window.focus(); } catch { /* ignore */ } + this.plugin.openMailView(); + // 点击通知即视为已处理:把这批邮件标记已读,避免再次提醒 + void this.markSeen(fresh); + }; + setTimeout(() => n.close(), 8000); + } catch { /* 某些环境不支持构造,忽略 */ } + } + } + + // 角标 + 状态栏 + this.updateBadges(); + } + + /** 点击通知/打开邮件后,把这批邮件在服务器和本地缓存都标记已读 */ + async markSeen(mails: MailSummary[]): Promise { + for (const m of mails) { + const acc = this.plugin.settings.accounts.find((a) => a.id === m.accountId); + if (!acc) continue; + try { + await this.plugin.mail.setSeen(acc, m.folder, m.uid, true); + } catch (e) { + // 服务器标记失败不影响本地状态更新 + const st = this.plugin.settings.states[m.accountId]; + const cached = st?.mails.find((x) => x.accountId === m.accountId && x.folder === m.folder && x.uid === m.uid); + if (cached) cached.seen = true; + this.plugin.scheduleSave(); + } + } + this.updateBadges(); + } + + /** 更新功能区角标和状态栏计数 */ + updateBadges(): void { + const s = this.plugin.settings; + const unread = Object.values(s.states).reduce( + (sum, st) => sum + (st?.mails?.filter((m) => !m.seen).length ?? 0), + 0, + ); + + // 侧边栏图标角标 + const icon = this.plugin.ribbonIconEl; + if (icon) { + const existing = icon.querySelector(".maildesk-badge"); + if (existing) existing.remove(); + if (s.notifyBadge && unread > 0) { + const badge = document.createElement("span"); + badge.className = "maildesk-badge"; + badge.textContent = unread > 99 ? "99+" : String(unread); + icon.appendChild(badge); + } + } + + // 状态栏 + if (s.notifyStatusBar) { + if (!this.statusBarEl) { + this.statusBarEl = this.plugin.addStatusBarItem(); + this.statusBarEl.addClass("maildesk-statusbar"); + this.statusBarEl.onclick = () => this.plugin.openMailView(); + } + this.statusBarEl.toggleClass("maildesk-statusbar-has-unread", unread > 0); + this.statusBarEl.setText(unread > 0 ? `✉ ${unread} 封未读` : "✉ 无未读"); + } else if (this.statusBarEl) { + this.statusBarEl.remove(); + this.statusBarEl = null; + } + + // 通知视图刷新角标(节流,避免 updateBadges 被频繁调用时反复重绘) + if (this.refreshTimer !== null) window.clearTimeout(this.refreshTimer); + this.refreshTimer = window.setTimeout(() => { + this.plugin.refreshView(); + this.refreshTimer = null; + }, 60); + } + + dispose(): void { + if (this.refreshTimer !== null) { + window.clearTimeout(this.refreshTimer); + this.refreshTimer = null; + } + if (this.statusBarEl) { + this.statusBarEl.remove(); + this.statusBarEl = null; + } + if (this.plugin.ribbonIconEl) { + this.plugin.ribbonIconEl.querySelector(".maildesk-badge")?.remove(); + } + } +} diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..4e5e16e --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,454 @@ +// --------------------------------------------------------------------------- +// 设置面板 +// --------------------------------------------------------------------------- +import { App, Notice, PluginSettingTab, Setting, Modal, TextComponent, SecretComponent } from "obsidian"; +import type MailDeskPlugin from "../main"; +import { + PROVIDERS, + guessProvider, + makeAccountId, + type MailAccount, + type ProviderPreset, +} from "./types"; + +export class MailDeskSettingTab extends PluginSettingTab { + constructor(app: App, private plugin: MailDeskPlugin) { + super(app, plugin); + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + + containerEl.createEl("h2", { cls: "maildesk-section-heading", text: "Mail Desk 设置" }); + + // ---- 通用 ---- + new Setting(containerEl) + .setName("自动收信间隔") + .setDesc("每隔多少分钟检查一次新邮件。设为 0 则关闭自动收信,只手动收取。") + .addSlider((slider) => slider + .setLimits(0, 60, 1) + .setValue(this.plugin.settings.pollInterval) + .setDynamicTooltip() + .onChange(async (v) => { + this.plugin.settings.pollInterval = v; + await this.plugin.saveSettings(); + this.plugin.restartPolling(); + })); + + new Setting(containerEl) + .setName("启动时收信") + .setDesc("打开 Obsidian 时立即检查一次新邮件。") + .addToggle((t) => t + .setValue(this.plugin.settings.syncOnStartup) + .onChange(async (v) => { + this.plugin.settings.syncOnStartup = v; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName("默认文件夹") + .setDesc("侧边栏默认展示的邮件文件夹,一般是 INBOX。") + .addText((t) => t + .setValue(this.plugin.settings.defaultFolder) + .onChange(async (v) => { + this.plugin.settings.defaultFolder = v || "INBOX"; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName("打开邮件时自动存笔记") + .setDesc("每次阅读邮件都自动在库里存一份 Markdown 笔记(MailDesk邮件/ 目录)。") + .addToggle((t) => t + .setValue(this.plugin.settings.autoSaveNote) + .onChange(async (v) => { + this.plugin.settings.autoSaveNote = v; + await this.plugin.saveSettings(); + })); + + // ---- 界面与布局 ---- + containerEl.createEl("h3", { cls: "maildesk-section-heading", text: "界面与布局" }); + + // 说明:本插件只在邮件面板可见期间临时加宽侧栏,离开即还原 + containerEl.createEl("p", { + cls: "maildesk-setting-hint", + text: "打开邮件面板时会自动把 Obsidian 左侧栏加宽到设定宽度(默认 1100px),一屏看全「账户栏 + 邮件列表 + 阅读栏」,不用每次手动拖。加宽用的是和 Obsidian 自身拖拽同一个属性,所以你随时可以拖边缘继续调宽,不会被插件拉回去;关闭面板或切到其它面板时还原成你原来的宽度。", + }); + + new Setting(containerEl) + .setName("打开时自动加宽侧栏") + .setDesc("只在邮件面板可见时生效。关闭后不改动侧栏,窄栏时面板切换为「列表 ↔ 阅读」模式。") + .addToggle((t) => t + .setValue(this.plugin.settings.dockAutoFit) + .onChange(async (v) => { + this.plugin.settings.dockAutoFit = v; + await this.plugin.saveSettings(); + if (v) this.plugin.fitDockForMailView(); + else this.plugin.restoreDockWidth(); + })); + + new Setting(containerEl) + .setName("自动加宽的目标宽度") + .setDesc("默认 1100px。实际宽度还会按窗口宽度的 62% 封顶,避免把主编辑区挤没;面板内阅读栏保底 340px,不够时会先压缩邮件列表。") + .addSlider((s) => s + .setLimits(520, 1800, 20) + .setValue(this.plugin.settings.dockFitWidth) + .setDynamicTooltip() + .onChange(async (v) => { + this.plugin.settings.dockFitWidth = v; + await this.plugin.saveSettings(); + this.plugin.retargetDockWidth(); + })); + + new Setting(containerEl) + .setName("邮件列表栏宽度") + .setDesc("三栏布局里中间邮件列表的宽度。也可直接在面板里拖动分隔条调整。") + .addSlider((s) => s + .setLimits(200, 600, 10) + .setValue(this.plugin.settings.listWidth) + .setDynamicTooltip() + .onChange(async (v) => { + this.plugin.settings.listWidth = v; + await this.plugin.saveSettings(); + this.plugin.refreshView(); + })); + + new Setting(containerEl) + .setName("账户栏宽度") + .setDesc("三栏布局里左侧账户/文件夹栏的宽度。也可直接在面板里拖动分隔条调整。") + .addSlider((s) => s + .setLimits(120, 320, 4) + .setValue(this.plugin.settings.sidebarWidth) + .setDynamicTooltip() + .onChange(async (v) => { + this.plugin.settings.sidebarWidth = v; + await this.plugin.saveSettings(); + this.plugin.refreshView(); + })); + + new Setting(containerEl) + .setName("调试日志") + .setDesc("在开发者控制台输出收信细节。排障时使用。") + .addToggle((t) => t + .setValue(this.plugin.settings.debug) + .onChange(async (v) => { + this.plugin.settings.debug = v; + await this.plugin.saveSettings(); + })); + + // ---- 提醒 ---- + containerEl.createEl("h3", { cls: "maildesk-section-heading", text: "新邮件提醒" }); + + new Setting(containerEl) + .setName("系统桌面通知") + .setDesc("通过系统通知弹出,Obsidian 最小化时也能看到(仅桌面端)。") + .addToggle((t) => t + .setValue(this.plugin.settings.notifySystem) + .onChange(async (v) => { + this.plugin.settings.notifySystem = v; + if (v) await this.plugin.requestNotificationPermission(); + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName("应用内 Notice") + .setDesc("在 Obsidian 右上角弹出提示条。") + .addToggle((t) => t + .setValue(this.plugin.settings.notifyNotice) + .onChange(async (v) => { + this.plugin.settings.notifyNotice = v; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName("侧边栏未读角标") + .setDesc("在左侧功能区的邮件图标上显示未读数字。") + .addToggle((t) => t + .setValue(this.plugin.settings.notifyBadge) + .onChange(async (v) => { + this.plugin.settings.notifyBadge = v; + await this.plugin.saveSettings(); + this.plugin.updateBadges(); + })); + + new Setting(containerEl) + .setName("底部状态栏计数") + .setDesc("在 Obsidian 底部状态栏常驻显示未读总数。") + .addToggle((t) => t + .setValue(this.plugin.settings.notifyStatusBar) + .onChange(async (v) => { + this.plugin.settings.notifyStatusBar = v; + await this.plugin.saveSettings(); + this.plugin.updateBadges(); + })); + + new Setting(containerEl) + .setName("汇总通知") + .setDesc('开启后一次收信只弹一条汇总(如"3 封新邮件"),关闭则每封各弹一条。') + .addToggle((t) => t + .setValue(this.plugin.settings.aggregateNotification) + .onChange(async (v) => { + this.plugin.settings.aggregateNotification = v; + await this.plugin.saveSettings(); + })); + + // ---- 账户 ---- + containerEl.createEl("h3", { cls: "maildesk-section-heading", text: "邮箱账户" }); + const desc = containerEl.createEl("p", { + cls: "maildesk-setting-hint", + text: "授权码保存在系统密钥链(设置 → Keychain),本项目只记录密钥名称,不存明文密码。QQ / 126 / 163 需在网页端先开启 IMAP/SMTP 服务并生成授权码。", + }); + + this.plugin.settings.accounts.forEach((account, idx) => { + this.renderAccount(containerEl, account, idx); + }); + + new Setting(containerEl) + .setClass("maildesk-add-account") + .addButton((b) => b + .setButtonText("+ 添加邮箱账户") + .setCta() + .onClick(() => { + new AccountModal(this.app, this.plugin, undefined, async (acc) => { + this.plugin.settings.accounts.push(acc); + await this.plugin.saveSettings(); + this.display(); + }).open(); + })); + } + + private renderAccount(containerEl: HTMLElement, account: MailAccount, idx: number) { + const s = new Setting(containerEl) + .setClass("maildesk-account-card") + .setName(`${account.enabled ? "" : "(已停用) "}${account.name}`) + .setDesc(`${account.email} · IMAP ${account.imapHost}:${account.imapPort}`) + .addToggle((t) => t + .setTooltip("启用 / 停用") + .setValue(account.enabled) + .onChange(async (v) => { + account.enabled = v; + await this.plugin.saveSettings(); + this.display(); + })) + .addExtraButton((b) => b + .setIcon("pencil") + .setTooltip("编辑") + .onClick(() => { + new AccountModal(this.app, this.plugin, account, async (updated) => { + this.plugin.settings.accounts[idx] = updated; + await this.plugin.saveSettings(); + this.display(); + }).open(); + })) + .addExtraButton((b) => b + .setIcon("trash") + .setTooltip("删除账户") + .onClick(async () => { + if (!confirm(`确定删除账户「${account.name}」?本地缓存邮件也会一起清除。`)) return; + delete this.plugin.settings.states[account.id]; + this.plugin.settings.accounts.splice(idx, 1); + await this.plugin.saveSettings(); + this.plugin.updateBadges(); + this.display(); + })); + + // 授权码选择行(SecretComponent) + new Setting(containerEl) + .setClass("maildesk-secret-row") + .setName("授权码(密钥链)") + .setDesc(`密钥名称:${account.secretId || "未设置"}。请先在 设置 → Keychain 创建,或在此选择。`) + .addComponent((el) => { + const comp = new SecretComponent(this.app, el) + .setValue(account.secretId) + .onChange(async (value) => { + account.secretId = value ?? ""; + await this.plugin.saveSettings(); + this.display(); + }); + return comp; + }); + + // 测试连接 + new Setting(containerEl) + .setClass("maildesk-secret-row") + .setName("连接测试") + .setDesc("验证 IMAP 收信和 SMTP 发信是否都能连通。") + .addButton((b) => b + .setButtonText("测试") + .onClick(async () => { + new Notice("正在测试连接…"); + const res = await this.plugin.mail.testConnection(account); + new Notice(res.ok ? "✓ IMAP / SMTP 均连接成功" : "✗ " + res.error, res.ok ? 4000 : 8000); + })); + + // 状态 + const state = this.plugin.settings.states[account.id]; + if (state) { + const last = state.lastSync ? new Date(state.lastSync).toLocaleString() : "从未"; + containerEl.createEl("p", { + cls: "maildesk-setting-hint", + text: `上次同步:${last} 已缓存 ${state.mails.length} 封${state.lastError ? " 上次错误:" + state.lastError : ""}`, + }); + } + } +} + +// --------------------------------------------------------------------------- +// 新增 / 编辑账户弹窗 +// --------------------------------------------------------------------------- +class AccountModal extends Modal { + private nameInput!: TextComponent; + private emailInput!: TextComponent; + private imapHostInput!: TextComponent; + private imapPortInput!: TextComponent; + private smtpHostInput!: TextComponent; + private smtpPortInput!: TextComponent; + private secretComp!: SecretComponent; + private fetchDaysInput!: TextComponent; + private selectedProvider: ProviderPreset = PROVIDERS[0]; + private draft: MailAccount; + private secretValue: string; + + constructor( + app: App, + private plugin: MailDeskPlugin, + existing: MailAccount | undefined, + private onSave: (acc: MailAccount) => void | Promise, + ) { + super(app); + this.draft = existing + ? { ...existing } + : { + id: makeAccountId(), + name: "", + email: "", + senderName: "", + imapHost: "imap.qq.com", + imapPort: 993, + smtpHost: "smtp.qq.com", + smtpPort: 465, + secure: true, + secretId: "", + fetchDays: 30, + enabled: true, + }; + if (existing) { + const p = PROVIDERS.find((x) => x.imapHost === existing.imapHost); + if (p) this.selectedProvider = p; + } + this.secretValue = this.draft.secretId; + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: this.draft.name ? "编辑邮箱账户" : "添加邮箱账户" }); + + new Setting(contentEl) + .setName("服务商预设") + .setDesc("选择后自动填入服务器参数,仍可手动修改。") + .addDropdown((d) => { + PROVIDERS.forEach((p, i) => d.addOption(String(i), p.name)); + d.setValue(String(PROVIDERS.indexOf(this.selectedProvider))); + d.onChange((v) => { + const p = PROVIDERS[Number(v)]; + this.selectedProvider = p; + this.imapHostInput.setValue(p.imapHost); + this.imapPortInput.setValue(String(p.imapPort)); + this.smtpHostInput.setValue(p.smtpHost); + this.smtpPortInput.setValue(String(p.smtpPort)); + this.hintEl.textContent = p.authHint; + if (p.helpUrl) { + this.hintEl.appendText(" 帮助:"); + this.hintEl.createEl("a", { text: p.helpUrl, href: p.helpUrl, attr: { target: "_blank" } }); + } + }); + }); + + new Setting(contentEl).setName("账户名称").addText((t) => { + this.nameInput = t.setValue(this.draft.name) + .setPlaceholder("如:我的 QQ 邮箱"); + }); + + new Setting(contentEl).setName("邮箱地址").addText((t) => { + this.emailInput = t.setValue(this.draft.email) + .setPlaceholder("you@qq.com") + .onChange((v) => { + const p = guessProvider(v); + if (p) { + this.selectedProvider = p; + this.imapHostInput.setValue(p.imapHost); + this.imapPortInput.setValue(String(p.imapPort)); + this.smtpHostInput.setValue(p.smtpHost); + this.smtpPortInput.setValue(String(p.smtpPort)); + this.hintEl.textContent = p.authHint; + } + }); + }); + + new Setting(contentEl).setName("发件人显示名").addText((t) => + t.setValue(this.draft.senderName).setPlaceholder("留空则使用账户名称")); + + new Setting(contentEl).setName("IMAP 服务器").addText((t) => { + this.imapHostInput = t.setValue(this.draft.imapHost); + }); + new Setting(contentEl).setName("IMAP 端口").addText((t) => { + this.imapPortInput = t.setValue(String(this.draft.imapPort)); + }); + new Setting(contentEl).setName("SMTP 服务器").addText((t) => { + this.smtpHostInput = t.setValue(this.draft.smtpHost); + }); + new Setting(contentEl).setName("SMTP 端口").addText((t) => { + this.smtpPortInput = t.setValue(String(this.draft.smtpPort)); + }); + + new Setting(contentEl) + .setName("授权码(密钥链)") + .setDesc("从系统密钥链选择。请先到 设置 → Keychain 创建一条密钥,值为邮箱授权码。") + .addComponent((el) => { + this.secretComp = new SecretComponent(this.app, el) + .setValue(this.draft.secretId) + .onChange((v) => { this.secretValue = v ?? ""; }); + return this.secretComp; + }); + + new Setting(contentEl) + .setName("收取范围(天)") + .setDesc("只拉取最近 N 天的邮件。QQ 官方建议 30 天以降低授权码泄露风险。0 = 不限。") + .addText((t) => { + this.fetchDaysInput = t.setValue(String(this.draft.fetchDays)); + }); + + this.hintEl = contentEl.createEl("p", { cls: "maildesk-setting-hint" }); + this.hintEl.textContent = this.selectedProvider.authHint; + + new Setting(contentEl) + .addButton((b) => b.setButtonText("取消").onClick(() => this.close())) + .addButton((b) => b.setButtonText("保存").setCta().onClick(async () => { + const email = this.emailInput.getValue().trim(); + if (!email || !email.includes("@")) { + new Notice("请填写有效的邮箱地址"); + return; + } + this.draft.name = this.nameInput.getValue().trim() || email; + this.draft.email = email; + this.draft.senderName = this.draft.senderName || this.draft.name; + this.draft.imapHost = this.imapHostInput.getValue().trim(); + this.draft.imapPort = Number(this.imapPortInput.getValue()) || 993; + this.draft.smtpHost = this.smtpHostInput.getValue().trim(); + this.draft.smtpPort = Number(this.smtpPortInput.getValue()) || 465; + this.draft.secretId = this.secretValue; + this.draft.fetchDays = Number(this.fetchDaysInput.getValue()) || 0; + this.draft.secure = this.draft.imapPort === 993; + this.draft.smtpSecure = this.draft.smtpPort === 465; + await this.onSave({ ...this.draft }); + this.close(); + })); + } + + private hintEl!: HTMLParagraphElement; + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..9009214 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,245 @@ +// --------------------------------------------------------------------------- +// 类型定义 +// --------------------------------------------------------------------------- + +/** 邮箱服务商预设 */ +export interface ProviderPreset { + name: string; + imapHost: string; + imapPort: number; + smtpHost: string; + smtpPort: number; + /** true = 隐式 SSL/TLS(993/465),false = STARTTLS(143/587) */ + secure: boolean; + helpUrl: string; + /** 授权码获取说明 */ + authHint: string; +} + +/** 单个邮箱账户配置(授权码不存这里,只存 secretStorage 的 id) */ +export interface MailAccount { + id: string; + /** 显示名称 */ + name: string; + /** 完整邮箱地址 */ + email: string; + /** 发件人显示名 */ + senderName: string; + imapHost: string; + imapPort: number; + smtpHost: string; + smtpPort: number; + /** IMAP 是否隐式 SSL/TLS(993=true,143=false) */ + secure: boolean; + /** SMTP 是否隐式 SSL/TLS(465=true,587=false 即 STARTTLS);旧配置缺省时回退到 secure */ + smtpSecure?: boolean; + /** secretStorage 中授权码的 id,值本身不落盘 */ + secretId: string; + /** 只拉取最近 N 天的邮件,0 = 不限。QQ 官方建议 30 */ + fetchDays: number; + enabled: boolean; +} + +/** 邮件摘要(列表用) */ +export interface MailSummary { + accountId: string; + folder: string; + uid: number; + subject: string; + from: string; + fromName: string; + to: string; + date: string; + snippet: string; + seen: boolean; + hasAttachment: boolean; + attachmentCount: number; +} + +/** 邮件正文详情 */ +export interface MailDetail extends MailSummary { + html: string; + text: string; + attachments: AttachmentInfo[]; +} + +export interface AttachmentInfo { + filename: string; + contentType: string; + size: number; +} + +/** 本地缓存的某个账户的收信状态 */ +export interface AccountState { + /** 已经提醒过 / 已入库的最大 UID,用于增量拉取 */ + lastUid: number; + /** 是否已完成首次同步(首次只记基线不提醒) */ + initialized: boolean; + /** 缓存的邮件列表 */ + mails: MailSummary[]; + /** 从服务器缓存的文件夹列表 */ + folders?: string[]; + lastSync: number; + lastError: string; +} + +/** 未发送完的草稿(仅存文字,不含附件) */ +export interface ComposeDraft { + to: string; + cc: string; + subject: string; + body: string; + savedAt: number; +} + +/** 插件设置(存 data.json,不含任何密钥) */ +export interface MailDeskSettings { + accounts: MailAccount[]; + states: Record; + /** 轮询间隔(分钟),0 = 不自动收信 */ + pollInterval: number; + /** 启动 Obsidian 时是否立即收信 */ + syncOnStartup: boolean; + /** 提醒开关 */ + notifySystem: boolean; + notifyNotice: boolean; + notifyBadge: boolean; + notifyStatusBar: boolean; + /** 系统通知是否只在后台时弹出(前台用 Notice) */ + systemNotificationOnlyWhenBackground: boolean; + /** 每封新信都弹通知,还是汇总一条 */ + aggregateNotification: boolean; + /** 邮件列表默认文件夹 */ + defaultFolder: string; + /** 列表默认只显示未读 */ + showUnreadOnly: boolean; + /** 打开邮件后是否自动存一份笔记到库 */ + autoSaveNote: boolean; + /** 账户/文件夹栏宽度(px),可拖拽 */ + sidebarWidth: number; + /** 邮件列表栏宽度(px),可拖拽 */ + listWidth: number; + /** + * 打开邮件面板时,是否把 Obsidian 左侧栏临时加宽到能同时显示三栏。 + * v1.1.6 起恢复该能力,但与旧实现(write 死 1060px 且关闭不回滚)不同: + * 只在邮件面板可见期间加宽,面板关闭 / 切到别的面板 / 插件卸载时精确还原原始宽度。 + */ + dockAutoFit: boolean; + /** 自动加宽的目标宽度(px);实际会再按窗口宽度约 62% 上限封顶 */ + dockFitWidth: number; + /** + * 右侧栏「健康宽度」记录(px),自动维护,不需要用户设置。 + * 用途:加宽左栏时 Obsidian 的 flex 会把右栏一起压窄(并写进 workspace.json), + * 导致其它插件的右栏内容挤乱;下次打开时按这个值把右栏恢复回来。 + */ + rightDockWidth?: number; + /** 上次未发完的草稿 */ + draft: ComposeDraft | null; + /** 布局设置版本号,用于迁移默认宽度 */ + layoutVersion?: number; + /** debug 日志 */ + debug: boolean; +} + +export const PROVIDERS: ProviderPreset[] = [ + { + name: "QQ 邮箱", + imapHost: "imap.qq.com", + imapPort: 993, + smtpHost: "smtp.qq.com", + smtpPort: 465, + secure: true, + helpUrl: "https://help.mail.qq.com/detail/0/1088", + authHint: "网页版 QQ 邮箱 → 设置 → 账号与安全 → 开启 IMAP/SMTP 服务 → 生成 16 位授权码。密码栏填授权码,不是 QQ 密码。", + }, + { + name: "126 邮箱", + imapHost: "imap.126.com", + imapPort: 993, + smtpHost: "smtp.126.com", + smtpPort: 465, + secure: true, + helpUrl: "https://mail.126.com", + authHint: "网页版 126 邮箱 → 设置 → POP3/SMTP/IMAP → 开启 IMAP/SMTP → 短信验证 → 获取客户端授权码。密码栏填授权码。", + }, + { + name: "163 邮箱", + imapHost: "imap.163.com", + imapPort: 993, + smtpHost: "smtp.163.com", + smtpPort: 465, + secure: true, + helpUrl: "https://mail.163.com", + authHint: "网页版 163 邮箱 → 设置 → POP3/SMTP/IMAP → 开启服务并获取授权码。", + }, + { + name: "Gmail", + imapHost: "imap.gmail.com", + imapPort: 993, + smtpHost: "smtp.gmail.com", + smtpPort: 465, + secure: true, + helpUrl: "https://myaccount.google.com/apppasswords", + authHint: "Google 账号 → 两步验证 → 应用专用密码。密码栏填 16 位应用专用密码。", + }, + { + name: "Outlook / Hotmail", + imapHost: "outlook.office365.com", + imapPort: 993, + smtpHost: "smtp.office365.com", + smtpPort: 587, + secure: false, + helpUrl: "https://account.microsoft.com/security", + authHint: "微软账户自 2024 年 9 月起第三方客户端拒绝普通密码,需应用专用密码。基础认证可能被禁用,建议用企业邮箱或应用密码。", + }, + { + name: "自定义 IMAP", + imapHost: "", + imapPort: 993, + smtpHost: "", + smtpPort: 465, + secure: true, + helpUrl: "", + authHint: "手动填写 IMAP / SMTP 服务器地址、端口及加密方式。", + }, +]; + +export const DEFAULT_SETTINGS: MailDeskSettings = { + accounts: [], + states: {}, + pollInterval: 5, + syncOnStartup: true, + notifySystem: true, + notifyNotice: true, + notifyBadge: true, + notifyStatusBar: true, + systemNotificationOnlyWhenBackground: false, + aggregateNotification: true, + defaultFolder: "INBOX", + showUnreadOnly: false, + autoSaveNote: false, + sidebarWidth: 132, + listWidth: 250, + dockAutoFit: true, + dockFitWidth: 1100, + rightDockWidth: 344, + draft: null, + layoutVersion: 3, + debug: false, +}; + +/** 生成账户 id */ +export function makeAccountId(): string { + return "acct-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 7); +} + +/** 根据邮箱地址猜测服务商预设 */ +export function guessProvider(email: string): ProviderPreset | undefined { + const domain = email.split("@")[1]?.toLowerCase() ?? ""; + if (domain === "qq.com" || domain === "foxmail.com") return PROVIDERS[0]; + if (domain === "126.com") return PROVIDERS[1]; + if (domain === "163.com" || domain === "yeah.net") return PROVIDERS[2]; + if (domain === "gmail.com" || domain === "googlemail.com") return PROVIDERS[3]; + if (domain === "outlook.com" || domain === "hotmail.com" || domain === "live.com") return PROVIDERS[4]; + return undefined; +} diff --git a/src/view.ts b/src/view.ts new file mode 100644 index 0000000..5045f5c --- /dev/null +++ b/src/view.ts @@ -0,0 +1,1276 @@ +// --------------------------------------------------------------------------- +// 侧边栏视图:账户/文件夹 + 邮件列表 + 阅读窗格 +// 布局策略:宽 → 三栏并排;窄 → 列表/阅读互斥切换(带返回) +// --------------------------------------------------------------------------- +import { ItemView, Notice, WorkspaceLeaf, Menu, setIcon, Modal } from "obsidian"; +import type MailDeskPlugin from "../main"; +import type { MailAccount, MailSummary, MailDetail } from "./types"; +import { ComposeModal } from "./compose"; + +export const VIEW_TYPE_MAIL = "maildesk-view"; + +/** 断点:< 560 视为窄栏,切「列表 ↔ 阅读」互斥 */ +const NARROW_BREAKPOINT = 560; + +const FOLDER_ICONS: Record = { + INBOX: "inbox", + Sent: "send", + "Sent Messages": "send", + "已发送": "send", + Drafts: "file-edit", + "草稿箱": "file-edit", + Trash: "trash", + "已删除": "trash", + Junk: "shield-alert", + "垃圾邮件": "shield-alert", + Archive: "archive", +}; + +/** 轻量确认弹窗,替代原生 confirm */ +class ConfirmModal extends Modal { + constructor( + app: import("obsidian").App, + private title: string, + private desc: string, + private onConfirm: () => void | Promise, + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.addClass("maildesk-confirm-modal"); + contentEl.createEl("div", { cls: "maildesk-confirm-title", text: this.title }); + contentEl.createEl("div", { cls: "maildesk-confirm-desc", text: this.desc }); + const actions = contentEl.createEl("div", { cls: "maildesk-confirm-actions" }); + const cancel = actions.createEl("button", { text: "取消" }); + cancel.onclick = () => this.close(); + const ok = actions.createEl("button", { cls: "mod-warning", text: "确定" }); + ok.onclick = async () => { + await this.onConfirm(); + this.close(); + }; + } + + onClose(): void { this.contentEl.empty(); } +} + +export class MailView extends ItemView { + private accountListEl!: HTMLElement; + private folderListEl!: HTMLElement; + private mailListEl!: HTMLElement; + private listColEl!: HTMLElement; + private readerColEl!: HTMLElement; + private readerEl!: HTMLElement; + private rootEl!: HTMLElement; + private searchInput!: HTMLInputElement; + private filterTabsEl!: HTMLElement; + private filterAllBtn: HTMLButtonElement | null = null; + private filterUnreadBtn: HTMLButtonElement | null = null; + private filterUnreadCountEl: HTMLElement | null = null; + private setReadBtnEl: HTMLButtonElement | null = null; + private deleteBtnEl: HTMLButtonElement | null = null; + private selectModeBtnEl: HTMLButtonElement | null = null; + private selectAllBtnEl: HTMLButtonElement | null = null; + /** 是否处于选择态(点击「选择」或「全选」后开启,复选框仅此时显示) */ + private selectionMode = false; + /** 正在批量处理(已读/删除)中,仅用于禁用批量按钮,不阻塞全选切换 */ + private processingSelection = false; + /** 多选中的邮件 key 集合:accountId|folder|uid */ + private selectedUids: Set = new Set(); + private selectedAccountId: string | null = null; + private selectedFolder = "INBOX"; + private selectedMail: MailDetail | null = null; + private currentMails: MailSummary[] = []; + private unreadOnly = false; + private searchQuery = ""; + private isNarrow = false; + private readerOpen = false; + /** 窄栏:账户/文件夹栏是否作为独立一屏显示 */ + private accountsPaneOpen = false; + private accountsBtnEl: HTMLButtonElement | null = null; + private accountsLabelEl: HTMLElement | null = null; + private dateCache = new Map(); + private toastTimer: number | null = null; + private themeObserver: MutationObserver | null = null; + + constructor(leaf: WorkspaceLeaf, private plugin: MailDeskPlugin) { + super(leaf); + } + + getViewType(): string { return VIEW_TYPE_MAIL; } + getDisplayText(): string { return "Mail Desk"; } + getIcon(): string { return "maildesk-mail"; } + + async onOpen(): Promise { + const root = this.contentEl; + root.empty(); + // 清掉上一次打开可能残留的布局态,避免重开时停「阅读态 / 账户屏」而看起来是空的 + root.removeClass("show-accounts"); + root.removeClass("reader-open"); + root.removeClass("is-narrow"); + root.addClass("maildesk-view"); + this.rootEl = root; + this.readerOpen = false; + this.accountsPaneOpen = false; + // 视图可能反复打开/关闭,按钮引用必须清空后重建 + this.filterAllBtn = null; + this.filterUnreadBtn = null; + this.filterUnreadCountEl = null; + this.setReadBtnEl = null; + this.deleteBtnEl = null; + this.selectModeBtnEl = null; + this.selectAllBtnEl = null; + this.accountsBtnEl = null; + this.accountsLabelEl = null; + this.selectionMode = false; + this.selectedUids.clear(); + this.processingSelection = false; + + // ---- 顶部工具栏 ---- + const header = root.createDiv("maildesk-toolbar"); + const title = header.createDiv("maildesk-toolbar-title"); + title.createSpan({ text: "Mail Desk" }); + // 返回按钮(仅窄栏、阅读态显示) + const backBtn = header.createEl("button", { + cls: "maildesk-icon-btn maildesk-back-btn", + attr: { "aria-label": "返回邮件列表", title: "返回列表" }, + }); + setIcon(backBtn, "arrow-left"); + backBtn.onclick = () => this.closeReader(); + // 账户/文件夹按钮(仅窄栏显示):窄栏放不下三栏时,账户栏改为独立一屏 + const accountsBtn = header.createEl("button", { + cls: "maildesk-icon-btn maildesk-accounts-btn", + attr: { "aria-label": "账户与文件夹", title: "账户与文件夹" }, + }); + setIcon(accountsBtn, "users"); + const accountsLabel = accountsBtn.createSpan({ cls: "maildesk-accounts-btn-label" }); + this.accountsBtnEl = accountsBtn; + this.accountsLabelEl = accountsLabel; + accountsBtn.onclick = () => this.toggleAccountsPane(); + const actions = header.createDiv("maildesk-toolbar-actions"); + this.iconButton(actions, "refresh-cw", "收取新邮件", (btn) => this.syncAll(btn)); + this.iconButton(actions, "square-pen", "写邮件", () => this.composeNew()); + this.iconButton(actions, "settings", "设置", () => this.plugin.openSettings()); + + // ---- 搜索 + 过滤行 ---- + const searchbar = root.createDiv("maildesk-searchbar"); + const searchWrap = searchbar.createDiv("maildesk-search-input"); + const input = searchWrap.createEl("input", { + type: "text", + attr: { placeholder: "搜索主题 / 发件人…" }, + }); + this.searchInput = input; + let searchTimer: number | null = null; + input.addEventListener("input", () => { + if (searchTimer !== null) window.clearTimeout(searchTimer); + searchTimer = window.setTimeout(() => { + this.searchQuery = input.value.trim().toLowerCase(); + this.renderMailList(); + }, 180); + }); + // 过滤行:「全部 / 未读 / 全选 / 设为已读」紧凑居中,全选在设为已读左侧 + const filterRow = searchbar.createDiv("maildesk-filter-row"); + this.filterTabsEl = filterRow.createDiv("maildesk-filter-tabs"); + this.renderFilterTabs(); + + // ---- 三栏 ---- + const body = root.createDiv("maildesk-body"); + const sidebar = body.createDiv("maildesk-sidebar"); + // 不显示「账户 / 文件夹」文案,直接展示邮箱账户列表 + this.accountListEl = sidebar.createDiv("maildesk-account-list"); + this.folderListEl = sidebar.createDiv("maildesk-folder-list"); + + const splitter1 = body.createDiv("maildesk-splitter maildesk-splitter-sidebar"); + this.setupSplitter(splitter1, "sidebar"); + + this.listColEl = body.createDiv("maildesk-list-col"); + this.mailListEl = this.listColEl.createDiv("maildesk-mail-list"); + + const splitter2 = body.createDiv("maildesk-splitter maildesk-splitter-list"); + this.setupSplitter(splitter2, "list"); + + this.readerColEl = body.createDiv("maildesk-reader-col"); + this.readerEl = this.readerColEl.createDiv("maildesk-reader"); + + // ---- 宽度 & 布局 ---- + this.applyColumnWidths(); + this.updateLayout(); + this.registerEvent(this.app.workspace.on("resize", () => this.updateLayout())); + // ResizeObserver:侧栏被拖动、窗口变化时实时重算布局 + if (typeof ResizeObserver !== "undefined") { + const ro = new ResizeObserver(() => this.updateLayout()); + ro.observe(root); + this.register(() => ro.disconnect()); + } + // 主题切换时重绘邮件正文 iframe(让正文配色跟随明暗主题) + this.themeObserver = new MutationObserver(() => this.refreshIframeTheme()); + this.themeObserver.observe(document.body, { attributes: true, attributeFilter: ["class"] }); + + this.renderAccounts(); + this.renderMailList(); + this.renderEmptyReader(); + // 打开面板时把侧栏加宽到能同时显示三栏(关闭/切走会精确还原,不影响别的面板) + this.plugin.fitDockForMailView(); + } + + /** + * 应用账户栏、列表栏宽度。 + * 关键:宽度不足时按优先级自动压缩(先压列表,再压账户栏), + * 保证右侧阅读栏始终有约 300px —— 点击邮件就能正常读,不会被挤成一条缝。 + * 压缩只影响本次显示,用户保存的设置值不变。 + */ + private applyColumnWidths(): void { + if (!this.rootEl) return; + // 拖分隔条过程中不要重算,否则手感会被“拉回去” + if (this.rootEl.hasClass("is-resizing")) return; + const available = this.contentEl.clientWidth; + let side = this.plugin.settings.sidebarWidth; + let list = this.plugin.settings.listWidth; + const MIN_READER = 340; + const MIN_LIST = 180; + const MIN_SIDE = 110; + const SPLITTERS = 16; // 两条分隔条,各 8px + if (available > 0) { + let over = side + list + MIN_READER + SPLITTERS - available; + if (over > 0) { + const cut = Math.min(over, Math.max(0, list - MIN_LIST)); + list -= cut; + over -= cut; + } + if (over > 0) { + const cut = Math.min(over, Math.max(0, side - MIN_SIDE)); + side -= cut; + } + } + this.rootEl.style.setProperty("--maildesk-sidebar-w", `${Math.round(side)}px`); + this.rootEl.style.setProperty("--maildesk-list-w", `${Math.round(list)}px`); + } + + /** + * 布局自适应: + * - 宽(>=560):三栏并排 + * - 窄(<560):账户栏、列表、阅读三者互斥 —— 默认显示列表, + * 点工具栏的账户按钮可切到「账户与文件夹」屏,选完账户/文件夹自动回列表 + */ + private updateLayout(): void { + if (!this.rootEl) return; + // 宽度变化时重算三栏分配(阅读栏保底 300px) + this.applyColumnWidths(); + const w = this.contentEl.clientWidth; + const narrow = w > 0 && w < NARROW_BREAKPOINT; + if (narrow !== this.isNarrow) { + this.isNarrow = narrow; + // 从窄切回宽:恢复三栏,清掉阅读互斥态与账户屏 + if (!narrow) { + this.readerOpen = false; + this.toggleAccountsPane(false); + } + } + this.rootEl.toggleClass("is-narrow", narrow); + this.rootEl.toggleClass("reader-open", narrow && this.readerOpen); + } + + /** 窄栏:切换「账户与文件夹」独立一屏(宽栏下无效,三栏本来就都可见) */ + private toggleAccountsPane(force?: boolean): void { + if (!this.rootEl) return; + const next = force ?? !this.accountsPaneOpen; + this.accountsPaneOpen = next; + this.rootEl.toggleClass("show-accounts", next); + this.accountsBtnEl?.toggleClass("is-active", next); + // 进入账户屏就退掉阅读态,避免屏幕状态打架 + if (next) this.closeReader(); + } + + /** 窄栏打开阅读:切到阅读视图 */ + private openReader(): void { + if (!this.isNarrow) return; + this.toggleAccountsPane(false); + this.readerOpen = true; + this.rootEl.addClass("reader-open"); + this.readerEl.scrollTop = 0; + } + + /** 窄栏返回列表 */ + private closeReader(): void { + this.readerOpen = false; + this.rootEl.removeClass("reader-open"); + } + + /** 拖拽分隔条调整宽度 */ + private setupSplitter(splitter: HTMLElement, which: "sidebar" | "list"): void { + let startX = 0; + let startW = 0; + let moved = false; + const readVar = (prop: string, fallback: number) => { + const v = parseInt(this.rootEl.style.getPropertyValue(prop), 10); + return isNaN(v) ? fallback : v; + }; + /** 拖拽上限:始终给阅读栏留 300px */ + const limits = () => { + const avail = this.contentEl.clientWidth || 0; + const side = readVar("--maildesk-sidebar-w", this.plugin.settings.sidebarWidth); + const list = readVar("--maildesk-list-w", this.plugin.settings.listWidth); + const MIN_READER = 340; + const SPLITTERS = 16; + return { + sidebarMax: Math.min(320, Math.max(120, avail - list - MIN_READER - SPLITTERS)), + listMax: Math.min(600, Math.max(180, avail - side - MIN_READER - SPLITTERS)), + }; + }; + const onMove = (ev: MouseEvent) => { + const delta = ev.clientX - startX; + if (Math.abs(delta) > 1) moved = true; + const lim = limits(); + if (which === "sidebar") { + const w = Math.max(120, Math.min(lim.sidebarMax, startW + delta)); + this.rootEl.style.setProperty("--maildesk-sidebar-w", `${Math.round(w)}px`); + } else { + const w = Math.max(180, Math.min(lim.listMax, startW + delta)); + this.rootEl.style.setProperty("--maildesk-list-w", `${Math.round(w)}px`); + } + }; + const onUp = () => { + document.removeEventListener("mousemove", onMove); + document.removeEventListener("mouseup", onUp); + splitter.removeClass("is-dragging"); + this.rootEl.removeClass("is-resizing"); + // 只是点了一下没真的拖动:不写设置,避免把「自适应压缩值」误存成用户偏好 + if (!moved) return; + const prop = which === "sidebar" ? "--maildesk-sidebar-w" : "--maildesk-list-w"; + const w = parseInt(this.rootEl.style.getPropertyValue(prop), 10); + if (!isNaN(w)) { + if (which === "sidebar") this.plugin.settings.sidebarWidth = w; + else this.plugin.settings.listWidth = w; + this.plugin.scheduleSave(); + } + }; + splitter.addEventListener("mousedown", (ev) => { + startX = ev.clientX; + moved = false; + const prop = which === "sidebar" ? "--maildesk-sidebar-w" : "--maildesk-list-w"; + const stored = parseInt(this.rootEl.style.getPropertyValue(prop), 10); + startW = !isNaN(stored) ? stored + : which === "sidebar" ? this.listColEl.parentElement?.querySelector(".maildesk-sidebar")?.clientWidth ?? 168 + : this.listColEl.clientWidth; + splitter.addClass("is-dragging"); + this.rootEl.addClass("is-resizing"); + document.addEventListener("mousemove", onMove); + document.addEventListener("mouseup", onUp); + // 别让 mousedown 冒泡到 Obsidian 的 leaf 拖拽逻辑(否则可能把面板拖成新窗口/新标签) + ev.preventDefault(); + ev.stopPropagation(); + }); + } + + private iconButton(parent: HTMLElement, icon: string, tip: string, cb: (btn: HTMLElement) => void): void { + const btn = parent.createEl("button", { cls: "maildesk-icon-btn", attr: { "aria-label": tip, title: tip } }); + setIcon(btn, icon); + btn.onclick = () => cb(btn); + } + + private renderFilterTabs(): void { + // 按钮只创建一次,之后仅更新状态/计数,避免重绘时节点被替换导致点击落空 + if (!this.filterAllBtn) { + const all = this.filterTabsEl.createEl("button", { cls: "maildesk-filter-tab", text: "全部" }); + all.onclick = () => { + this.resetSelection(false); + this.unreadOnly = false; + this.renderFilterTabs(); + this.renderMailList(); + }; + this.filterAllBtn = all; + + const unread = this.filterTabsEl.createEl("button", { cls: "maildesk-filter-tab" }); + unread.appendText("未读"); + this.filterUnreadCountEl = unread.createSpan({ cls: "maildesk-tab-count", text: "0" }); + unread.onclick = () => { + this.resetSelection(false); + this.unreadOnly = true; + this.renderFilterTabs(); + this.renderMailList(); + }; + this.filterUnreadBtn = unread; + + const selectMode = this.filterTabsEl.createEl("button", { + cls: "maildesk-select-mode-btn", + attr: { title: "进入选择模式,逐封勾选要操作的邮件" }, + }); + selectMode.appendText("选择"); + selectMode.onclick = () => this.toggleSelectMode(); + this.selectModeBtnEl = selectMode; + + const selectAll = this.filterTabsEl.createEl("button", { + cls: "maildesk-select-all-btn", + attr: { title: "全选当前列表,再次点击取消" }, + }); + selectAll.appendText("全选"); + selectAll.onclick = () => this.toggleSelectAll(); + this.selectAllBtnEl = selectAll; + + const setRead = this.filterTabsEl.createEl("button", { + cls: "maildesk-set-read-btn", + attr: { title: "把勾选的邮件标为已读" }, + }); + setRead.onclick = () => this.markSelectedRead(); + this.setReadBtnEl = setRead; + + const del = this.filterTabsEl.createEl("button", { + cls: "maildesk-delete-btn", + attr: { title: "删除勾选的邮件(从服务器删除)" }, + }); + del.onclick = () => this.deleteSelected(); + this.deleteBtnEl = del; + } + this.filterAllBtn.toggleClass("is-active", !this.unreadOnly); + this.filterUnreadBtn?.toggleClass("is-active", this.unreadOnly); + const unreadCount = this.getCurrentAccountMails().filter((m) => !m.seen).length; + this.filterUnreadCountEl?.setText(String(unreadCount)); + this.updateSelectionButtons(); + this.updateBulkButtons(); + } + + /** 渲染账户 + 文件夹 */ + renderAccounts(): void { + if (!this.accountListEl) return; + this.accountListEl.empty(); + const accounts = this.plugin.settings.accounts.filter((a) => a.enabled); + if (!accounts.length) { + this.renderListEmpty(this.accountListEl, "mail", "还没有账户", "点右上角设置添加邮箱账户"); + this.folderListEl?.empty(); + this.accountsLabelEl?.setText("账户"); + return; + } + if (!this.selectedAccountId || !accounts.find((a) => a.id === this.selectedAccountId)) { + this.selectedAccountId = accounts[0].id; + } + // 窄栏账户按钮上显示当前账户名,便于一眼确认在看哪个邮箱 + const current = accounts.find((a) => a.id === this.selectedAccountId); + this.accountsLabelEl?.setText(current ? current.name : "账户"); + + for (const acc of accounts) { + const row = this.accountListEl.createDiv("maildesk-account-row"); + row.toggleClass("is-active", acc.id === this.selectedAccountId); + row.createSpan({ cls: "maildesk-account-dot" }); + const texts = row.createDiv({ cls: "maildesk-account-name" }); + texts.createDiv({ text: acc.name }); + texts.createDiv({ cls: "maildesk-account-email", text: acc.email }); + const state = this.plugin.settings.states[acc.id]; + const unread = state?.mails?.filter((m) => !m.seen).length ?? 0; + if (unread > 0) row.createSpan({ cls: "maildesk-account-unread", text: unread > 99 ? "99+" : String(unread) }); + row.onclick = () => { + this.selectAccount(acc.id); + // 窄栏:选完账户自动回到邮件列表 + this.toggleAccountsPane(false); + }; + } + this.renderFolders(); + } + + /** 切换账户(账户栏点击 / 窄栏下拉共用) */ + private selectAccount(id: string): void { + if (this.selectedAccountId === id) return; + this.selectedAccountId = id; + this.selectedFolder = this.plugin.settings.defaultFolder || "INBOX"; + this.selectedMail = null; + this.clearBulkBusy(); + this.resetSelection(false); + this.searchQuery = ""; + if (this.searchInput) this.searchInput.value = ""; + this.closeReader(); + this.renderAccounts(); + this.renderMailList(); + this.renderEmptyReader(); + } + + private renderFolders(): void { + if (!this.folderListEl) return; + this.folderListEl.empty(); + if (!this.selectedAccountId) return; + const state = this.plugin.settings.states[this.selectedAccountId]; + const defaults = ["INBOX", "Sent", "Drafts", "Trash"]; + const fromCache = state?.mails?.map((m) => m.folder).filter(Boolean) ?? []; + const fromServer = state?.folders ?? []; + const folders = Array.from(new Set([...defaults, ...fromServer, ...fromCache])); + + for (const f of folders) { + const row = this.folderListEl.createDiv("maildesk-folder-row"); + row.toggleClass("is-active", f === this.selectedFolder); + const iconEl = row.createSpan({ cls: "maildesk-folder-icon" }); + setIcon(iconEl, FOLDER_ICONS[f] || "folder"); + row.createSpan({ cls: "maildesk-folder-name", text: this.folderLabel(f) }); + const count = (state?.mails ?? []).filter((m) => m.folder === f && !m.seen).length; + if (count > 0) row.createSpan({ cls: "maildesk-folder-count", text: String(count) }); + row.onclick = () => { + // 窄栏:选完文件夹自动回到邮件列表 + this.toggleAccountsPane(false); + if (this.selectedFolder === f) return; + this.selectedFolder = f; + this.selectedMail = null; + this.clearBulkBusy(); + this.resetSelection(false); + this.closeReader(); + this.renderFolders(); + this.renderMailList(); + this.renderEmptyReader(); + }; + } + } + + /** 从服务器拉取真实文件夹列表 */ + private async refreshFoldersFromServer(silent = false): Promise { + if (!this.selectedAccountId) return; + const acc = this.plugin.settings.accounts.find((a) => a.id === this.selectedAccountId); + if (!acc) return; + try { + const folders = await this.plugin.mail.listFolders(acc); + const state = this.plugin.settings.states[acc.id]; + if (state) { + state.folders = folders; + this.plugin.scheduleSave(); + } + this.renderFolders(); + if (!silent) new Notice(`已加载 ${folders.length} 个文件夹`); + } catch (e) { + if (!silent) new Notice("加载文件夹失败:" + (e instanceof Error ? e.message : String(e)), 6000); + } + } + + private folderLabel(folder: string): string { + const labels: Record = { + INBOX: "收件箱", + Sent: "已发送", + "Sent Messages": "已发送", + Drafts: "草稿箱", + Trash: "已删除", + Junk: "垃圾邮件", + Archive: "归档", + }; + return labels[folder] || folder; + } + + private getCurrentAccountMails(): MailSummary[] { + if (!this.selectedAccountId) return []; + return this.plugin.settings.states[this.selectedAccountId]?.mails ?? []; + } + + // ---- 多选 / 批量已读 ---- + + private mailKey(m: MailSummary): string { + return `${m.accountId}|${m.folder}|${m.uid}`; + } + + /** 切换单封邮件的选中态(全选后可逐个取消勾选) */ + private toggleSelect(m: MailSummary, check: HTMLInputElement, row: HTMLElement): void { + const key = this.mailKey(m); + const checked = check.checked; + if (checked) this.selectedUids.add(key); + else this.selectedUids.delete(key); + row.toggleClass("is-checked", checked); + this.updateSelectionButtons(); + this.updateBulkButtons(); + } + + /** 更新「选择 / 全选」两个按钮的文案与高亮 */ + private updateSelectionButtons(): void { + if (this.selectModeBtnEl) { + this.selectModeBtnEl.textContent = this.selectionMode ? "取消选择" : "选择"; + this.selectModeBtnEl.toggleClass("is-active", this.selectionMode); + } + if (this.selectAllBtnEl) { + const mails = this.currentMails; + const allSelected = this.selectionMode && mails.length > 0 + && mails.every((m) => this.selectedUids.has(this.mailKey(m))); + this.selectAllBtnEl.textContent = allSelected ? "取消全选" : "全选"; + this.selectAllBtnEl.toggleClass("is-active", allSelected); + } + } + + /** 更新「设为已读 / 删除」按钮上的选中计数与高亮 */ + private updateBulkButtons(): void { + const n = this.selectedUids.size; + if (this.setReadBtnEl) { + this.setReadBtnEl.textContent = n > 0 ? `设为已读 (${n})` : "设为已读"; + this.setReadBtnEl.toggleClass("is-ready", n > 0); + } + if (this.deleteBtnEl) { + this.deleteBtnEl.textContent = n > 0 ? `删除 (${n})` : "删除"; + this.deleteBtnEl.toggleClass("is-ready", n > 0); + } + } + + /** 退出选择态,恢复默认(不显示复选框) */ + private resetSelection(rerender = true): void { + this.selectedUids.clear(); + this.selectionMode = false; + this.listColEl?.removeClass("is-selecting"); + this.updateSelectionButtons(); + this.updateBulkButtons(); + if (rerender) this.renderMailList(); + } + + /** 无论批量操作成功失败,都彻底复位忙碌状态(供 finally / 切账户调用) */ + private clearBulkBusy(): void { + this.processingSelection = false; + this.setReadBtnEl?.removeClass("is-busy"); + this.deleteBtnEl?.removeClass("is-busy"); + } + + /** 点击「选择」:进入手动选择态(显示复选框但不预选),再次点击退出选择态 */ + private toggleSelectMode(): void { + if (this.selectionMode) { this.resetSelection(); return; } + this.selectionMode = true; + this.selectedUids.clear(); + this.listColEl?.addClass("is-selecting"); + this.updateSelectionButtons(); + this.updateBulkButtons(); + this.renderMailList(); + } + + /** 点击「全选」:进入选择态并勾选当前列表全部,再次点击取消全选(保留选择态,复选框仍在) */ + private toggleSelectAll(): void { + if (!this.selectionMode) { + this.selectionMode = true; + this.listColEl?.addClass("is-selecting"); + } + const mails = this.currentMails; + const allSelected = mails.length > 0 && mails.every((m) => this.selectedUids.has(this.mailKey(m))); + if (allSelected) this.selectedUids.clear(); + else this.selectedUids = new Set(mails.map((m) => this.mailKey(m))); + this.updateSelectionButtons(); + this.updateBulkButtons(); + this.renderMailList(); + } + + /** 把勾选的邮件标为已读(服务器 + 本地缓存) */ + private async markSelectedRead(): Promise { + if (this.processingSelection) return; + const targets = this.currentMails.filter((m) => this.selectedUids.has(this.mailKey(m))); + if (!targets.length) { this.toast("请先点「选择」或「全选」勾选邮件"); return; } + const count = targets.length; + // 先退出选择态,防止连续点击重复提交同一批邮件 + this.resetSelection(false); + this.renderMailList(); + this.processingSelection = true; + this.setReadBtnEl?.addClass("is-busy"); + try { + await this.batchSetSeen(targets, `已标 ${count} 封为已读`); + } finally { + // 无论成功/失败/异常,都必须复位,否则全选等后续操作永久失效 + this.clearBulkBusy(); + } + } + + /** 删除勾选的邮件(服务器 + 本地缓存),适用「全选」 */ + private async deleteSelected(): Promise { + if (this.processingSelection) return; + const targets = this.currentMails.filter((m) => this.selectedUids.has(this.mailKey(m))); + if (!targets.length) { this.toast("请先点「选择」或「全选」勾选邮件"); return; } + const count = targets.length; + new ConfirmModal( + this.app, + "删除邮件", + `确定删除选中的 ${count} 封邮件?此操作会从服务器删除,无法撤销。`, + async () => { + this.resetSelection(false); + this.renderMailList(); + this.processingSelection = true; + this.deleteBtnEl?.addClass("is-busy"); + try { + await this.batchDelete(targets); + } finally { + this.clearBulkBusy(); + } + }, + ).open(); + } + + /** 批量删除:按账户+文件夹分组,单连接批量删除,最后统一重绘 */ + private async batchDelete(mails: MailSummary[]): Promise { + // 按 accountId + folder 分组,同一分组复用一个 IMAP 连接 + const groups = new Map(); + let noAccount = 0; + for (const m of mails) { + const acc = this.getAccount(m); + if (!acc) { noAccount++; continue; } + const gkey = `${acc.id}|${m.folder}`; + let g = groups.get(gkey); + if (!g) { g = { acc, folder: m.folder, items: [] }; groups.set(gkey, g); } + g.items.push(m); + } + + let ok = 0; + let failed = noAccount; + for (const g of groups.values()) { + try { + const deleted = await this.plugin.mail.deleteMails( + g.acc, g.folder, g.items.map((m) => m.uid), + ); + ok += deleted.length; + failed += g.items.length - deleted.length; + // 删除成功的从本地缓存与当前列表移除 + const deletedSet = new Set(deleted); + const state = this.plugin.settings.states[g.acc.id]; + if (state) { + state.mails = state.mails.filter( + (x) => !(x.folder === g.folder && deletedSet.has(x.uid)), + ); + } + this.currentMails = this.currentMails.filter( + (x) => !(x.folder === g.folder && deletedSet.has(x.uid)), + ); + for (const m of g.items) { + if (deletedSet.has(m.uid) && this.selectedMail?.uid === m.uid && this.selectedMail?.accountId === g.acc.id) { + this.selectedMail = null; + } + } + } catch { + // 整组连接失败:按失败计数,本地保持原样,下次同步会纠正 + failed += g.items.length; + } + } + this.plugin.scheduleSave(); + this.renderMailList(); + this.renderFolders(); + this.plugin.updateBadges(); + if (!this.selectedMail) this.renderEmptyReader(); + if (failed > 0) { + this.showError("部分邮件删除失败", new Error(`${failed} 封删除失败(服务器连接或权限问题)`)); + } else { + this.toast(`✓ 已删除 ${ok} 封邮件`); + } + } + + /** 批量标记已读:逐封同步服务器并更新本地缓存,失败只影响单封 */ + private async batchSetSeen(mails: MailSummary[], successMsg: string): Promise { + let ok = 0; + let failed = 0; + for (const m of mails) { + const acc = this.getAccount(m); + let serverOk = false; + if (acc) { + try { + await this.plugin.mail.setSeen(acc, m.folder, m.uid, true); + serverOk = true; + } catch { /* 服务器失败仍更新本地缓存 */ } + } + // 找到本地缓存对象并更新(m 本身就是缓存引用,双保险) + const cached = this.getCurrentAccountMails().find( + (x) => x.accountId === m.accountId && x.folder === m.folder && x.uid === m.uid, + ); + if (cached) cached.seen = true; + m.seen = true; + if (serverOk || !acc) ok++; else failed++; + } + this.plugin.scheduleSave(); + this.renderMailList(); + this.renderFolders(); + this.plugin.updateBadges(); + if (failed > 0) { + this.showError("部分邮件同步失败", new Error(`${failed} 封服务器标记失败,已更新本地状态`)); + } else { + this.toast(`✓ ${successMsg}`); + } + } + + /** 渲染邮件列表 */ + renderMailList(): void { + if (!this.mailListEl) return; + this.mailListEl.empty(); + let mails = this.getCurrentAccountMails().filter((m) => m.folder === this.selectedFolder); + if (this.unreadOnly) mails = mails.filter((m) => !m.seen); + if (this.searchQuery) { + mails = mails.filter((m) => + (m.subject || "").toLowerCase().includes(this.searchQuery) || + (m.fromName || "").toLowerCase().includes(this.searchQuery) || + (m.from || "").toLowerCase().includes(this.searchQuery) || + (m.snippet || "").toLowerCase().includes(this.searchQuery), + ); + } + this.currentMails = mails.sort((a, b) => + new Date(b.date).getTime() - new Date(a.date).getTime(), + ); + + if (!this.currentMails.length) { + if (this.searchQuery) { + this.renderListEmpty(this.mailListEl, "search", "没有匹配的邮件", "换个关键词试试"); + } else if (this.unreadOnly) { + this.renderListEmpty(this.mailListEl, "check-check", "没有未读邮件", "全部都读完啦"); + } else { + this.renderListEmpty(this.mailListEl, "inbox", "文件夹是空的", "点上方刷新收取新邮件"); + } + this.renderFilterTabs(); + return; + } + + const frag = document.createDocumentFragment(); + for (const m of this.currentMails) { + const row = document.createElement("div"); + row.className = "maildesk-mail-row"; + row.toggleClass("is-unread", !m.seen); + row.toggleClass("is-selected", this.selectedMail?.uid === m.uid && this.selectedMail?.accountId === m.accountId); + const key = this.mailKey(m); + row.toggleClass("is-checked", this.selectedUids.has(key)); + + const top = row.createDiv("maildesk-mail-row-top"); + // 多选框:点击只切换选中,不打开邮件 + const check = top.createEl("input", { + type: "checkbox", + cls: "maildesk-mail-check", + attr: { "aria-label": "选中此邮件", title: "选中此邮件" }, + }); + check.checked = this.selectedUids.has(key); + check.onclick = (ev) => { + ev.stopPropagation(); + this.toggleSelect(m, check, row); + }; + top.createSpan({ cls: "maildesk-mail-from", text: m.fromName || m.from || "(未知)" }); + top.createSpan({ cls: "maildesk-mail-date", text: this.formatDate(m.date) }); + row.createDiv({ cls: "maildesk-mail-subject", text: m.subject }); + if (m.snippet) row.createDiv({ cls: "maildesk-mail-snippet", text: m.snippet }); + const footer = row.createDiv("maildesk-mail-row-foot"); + if (m.attachmentCount > 0) { + const att = footer.createSpan({ cls: "maildesk-mail-att" }); + setIcon(att, "paperclip"); + att.appendText(String(m.attachmentCount)); + } + if (!m.seen) { + const dot = footer.createSpan({ cls: "maildesk-unread-dot" }); + dot.title = "未读"; + } + + row.onclick = () => this.openMail(m); + row.oncontextmenu = (ev) => this.showMailMenu(ev, m); + frag.appendChild(row); + } + this.mailListEl.appendChild(frag); + this.renderFilterTabs(); + } + + private showMailMenu(ev: MouseEvent, m: MailSummary): void { + const acc = this.getAccount(m); + if (!acc) return; + const menu = new Menu(); + menu.addItem((item) => item.setTitle(m.seen ? "标为未读" : "标为已读").setIcon(m.seen ? "mail" : "checkmark") + .onClick(async () => { + try { + await this.plugin.mail.setSeen(acc, m.folder, m.uid, !m.seen); + m.seen = !m.seen; + this.renderMailList(); + this.renderFolders(); + this.plugin.updateBadges(); + } catch (e) { this.showError("操作失败", e); } + })); + menu.addItem((item) => item.setTitle("存为笔记").setIcon("file-plus") + .onClick(async () => { + try { + const detail = await this.plugin.mail.getMail(acc, m.folder, m.uid, false); + if (detail) await this.saveAsNote(detail); + } catch (e) { this.showError("保存失败", e); } + })); + menu.addSeparator(); + menu.addItem((item) => item.setTitle("删除").setIcon("trash") + .onClick(() => { + new ConfirmModal(this.app, "删除邮件", `确定删除「${m.subject}」?此操作会从服务器删除。`, async () => { + try { + await this.plugin.mail.deleteMail(acc, m.folder, m.uid); + if (this.selectedMail?.uid === m.uid) this.selectedMail = null; + this.renderMailList(); + this.plugin.updateBadges(); + this.toast("邮件已删除"); + } catch (e) { this.showError("删除失败", e); } + }).open(); + })); + menu.showAtMouseEvent(ev); + } + + private getAccount(m: MailSummary): MailAccount | undefined { + return this.plugin.settings.accounts.find((a) => a.id === m.accountId); + } + + private dateCacheKey(iso: string): string { + const d = new Date(iso); + return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; + } + + private formatDate(iso: string): string { + try { + const key = this.dateCacheKey(iso); + const cached = this.dateCache.get(iso + "|" + key); + if (cached) return cached; + const d = new Date(iso); + const now = new Date(); + let result: string; + if (d.toDateString() === now.toDateString()) { + result = d.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit", hour12: false }); + } else if (now.getTime() - d.getTime() < 6 * 86400000) { + result = d.toLocaleDateString("zh-CN", { weekday: "short" }); + } else if (d.getFullYear() === now.getFullYear()) { + result = d.toLocaleDateString("zh-CN", { month: "2-digit", day: "2-digit" }); + } else { + result = d.toLocaleDateString("zh-CN", { year: "2-digit", month: "2-digit", day: "2-digit" }); + } + if (this.dateCache.size > 500) this.dateCache.clear(); + this.dateCache.set(iso + "|" + key, result); + return result; + } catch { return ""; } + } + + /** 打开并阅读邮件 */ + private async openMail(m: MailSummary): Promise { + const acc = this.getAccount(m); + if (!acc) return; + this.selectedMail = null; + this.markRowSelected(m); + this.renderReaderLoading(); + this.openReader(); // 窄栏立即切到阅读视图 + + try { + const detail = await this.plugin.mail.getMail(acc, m.folder, m.uid, true); + if (!detail) throw new Error("无法读取邮件"); + this.selectedMail = detail; + await this.renderReader(detail); + m.seen = true; + this.markRowSelected(m); + this.renderFolders(); + this.renderFilterTabs(); + this.plugin.updateBadges(); + if (this.plugin.settings.autoSaveNote) await this.saveAsNote(detail, true); + } catch (e) { + this.readerEl.empty(); + this.readerEl.createEl("div", { cls: "maildesk-empty-reader", text: "读取失败:" + (e instanceof Error ? e.message : String(e)) }); + } + } + + private markRowSelected(m: MailSummary): void { + if (!this.mailListEl) return; + const rows = this.mailListEl.querySelectorAll(".maildesk-mail-row"); + rows.forEach((row, i) => { + const item = this.currentMails[i]; + row.toggleClass("is-selected", !!item && item.uid === m.uid && item.accountId === m.accountId); + }); + } + + private renderReaderLoading(): void { + this.readerEl.empty(); + const wrap = this.readerEl.createDiv("maildesk-loading"); + wrap.createSpan({ cls: "maildesk-spinner" }); + wrap.createSpan({ text: "加载中…" }); + } + + private async renderReader(mail: MailDetail): Promise { + this.readerEl.empty(); + const acc = this.getAccount(mail); + + // 操作栏:左侧动作组(回复/回复全部/转发),右侧动作组(存为笔记/设为已读/删除) + const bar = this.readerEl.createDiv("maildesk-reader-bar"); + if (acc) { + const leftGroup = bar.createDiv("maildesk-reader-bar-left"); + this.textButton(leftGroup, "回复", "reply", () => new ComposeModal(this.app, this.plugin, { kind: "reply", account: acc, mail, all: false }).open()); + this.textButton(leftGroup, "回复全部", "reply-all", () => new ComposeModal(this.app, this.plugin, { kind: "reply", account: acc, mail, all: true }).open()); + this.textButton(leftGroup, "转发", "corner-up-right", () => new ComposeModal(this.app, this.plugin, { kind: "forward", account: acc, mail }).open()); + const rightGroup = bar.createDiv("maildesk-reader-bar-right"); + this.textButton(rightGroup, "存为笔记", "file-plus", () => this.saveAsNote(mail)); + this.textButton(rightGroup, "设为已读", "mail", async () => { + try { + await this.plugin.mail.setSeen(acc, mail.folder, mail.uid, false); + mail.seen = false; + const cached = this.getCurrentAccountMails().find((x) => x.uid === mail.uid && x.folder === mail.folder); + if (cached) cached.seen = false; + this.renderMailList(); + this.renderFolders(); + this.plugin.updateBadges(); + } catch (e) { this.showError("操作失败", e); } + }); + this.textButton(rightGroup, "删除", "trash-2", () => { + new ConfirmModal(this.app, "删除邮件", `确定删除「${mail.subject}」?此操作会从服务器删除。`, async () => { + try { + await this.plugin.mail.deleteMail(acc, mail.folder, mail.uid); + if (this.selectedMail?.uid === mail.uid && this.selectedMail?.accountId === mail.accountId) { + this.selectedMail = null; + this.renderEmptyReader(); + } + this.renderMailList(); + this.renderFolders(); + this.renderFilterTabs(); + this.plugin.updateBadges(); + this.toast("邮件已删除"); + } catch (e) { this.showError("删除失败", e); } + }).open(); + }); + } + + // 头信息 + const header = this.readerEl.createDiv("maildesk-reader-header"); + header.createEl("h2", { text: mail.subject }); + const meta = header.createDiv("maildesk-reader-meta"); + const row = meta.createDiv("maildesk-reader-meta-row"); + const initial = (mail.fromName || mail.from || "?").trim().charAt(0).toUpperCase(); + row.createSpan({ cls: "maildesk-meta-avatar", text: initial }); + const main = row.createDiv("maildesk-meta-main"); + main.createSpan({ cls: "maildesk-meta-name", text: mail.fromName || mail.from || "(未知)" }); + main.createSpan({ cls: "maildesk-meta-addr", text: `${mail.from} → ${mail.to}` }); + row.createSpan({ cls: "maildesk-meta-date", text: new Date(mail.date).toLocaleString("zh-CN") }); + + // 附件 + if (mail.attachments.length) { + const attWrap = this.readerEl.createDiv("maildesk-reader-attachments"); + const label = attWrap.createSpan({ cls: "maildesk-att-label" }); + setIcon(label, "paperclip"); + label.appendText(` ${mail.attachments.length} 个附件`); + for (const att of mail.attachments) { + const btn = attWrap.createEl("button", { cls: "maildesk-att-chip" }); + setIcon(btn, "download"); + btn.appendText(`${att.filename} (${this.formatSize(att.size)})`); + btn.onclick = () => this.downloadAttachment(acc, mail, att.filename); + } + } + + // 正文 + const content = this.readerEl.createDiv("maildesk-reader-content"); + if (mail.html) { + const iframe = content.createEl("iframe", { cls: "maildesk-mail-iframe" }); + iframe.setAttribute("sandbox", "allow-same-origin"); + iframe.setAttribute("title", "邮件正文"); + iframe.dataset.theme = document.body.classList.contains("theme-dark") ? "dark" : "light"; + iframe.srcdoc = this.buildMailHtml(mail.html); + } else { + content.createEl("pre", { cls: "maildesk-mail-text", text: mail.text || "(无正文)" }); + } + } + + /** 主题切换时,只替换 iframe 的 srcdoc,不重绘整个阅读窗格 */ + private refreshIframeTheme(): void { + if (!this.selectedMail?.html) return; + const iframe = this.readerEl?.querySelector("iframe.maildesk-mail-iframe") as HTMLIFrameElement | null; + if (!iframe) return; + const theme = document.body.classList.contains("theme-dark") ? "dark" : "light"; + if (iframe.dataset.theme === theme) return; + iframe.dataset.theme = theme; + iframe.srcdoc = this.buildMailHtml(this.selectedMail.html); + } + + /** + * 构建邮件正文 HTML。直接从 Obsidian 当前主题读取 CSS 变量并注入, + * 让正文真正的深浅色适配(而不是整块 filter 反色——那样连图片都会变色)。 + */ + private buildMailHtml(html: string): string { + const clean = this.sanitizeHtml(html); + const cs = getComputedStyle(document.body); + const dark = document.body.classList.contains("theme-dark"); + const v = (name: string, fallback: string) => cs.getPropertyValue(name).trim() || fallback; + const bg = v("--background-primary", dark ? "#1e1e1e" : "#ffffff"); + const bgAlt = v("--background-secondary", dark ? "#252525" : "#f5f5f5"); + const fg = v("--text-normal", dark ? "#dcddde" : "#222222"); + const muted = v("--text-muted", dark ? "#999999" : "#666666"); + const link = v("--text-accent", v("--interactive-accent", dark ? "#7b9ff5" : "#185fa5")); + const border = v("--background-modifier-border", dark ? "#3a3a3a" : "#dddddd"); + const accent = v("--interactive-accent", dark ? "#7b9ff5" : "#185fa5"); + const fontText = v("--font-text", "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif"); + const scale = v("--font-ui-size", "14px"); + + // 基础样式:保证没有内联样式的邮件也有正常观感与响应式布局 + const base = ``; + + // 主题覆盖:放在正文「之后」,用 !important 压过邮件自带的内联样式。 + // 深色下重点处理:白底/黑字/深色文字/边框/表格,一律转成主题配色,避免刺眼白块。 + const override = dark ? `` : ``; + + return `${base}${clean}${override}`; + } + + private sanitizeHtml(html: string): string { + return html + .replace(//gi, "") + // 保留 `) + .replace(/]*>/gi, "") + .replace(/]*>/gi, "") + .replace(/\son\w+\s*=\s*["'][^"']*["']/gi, "") + .replace(/javascript:/gi, ""); + } + + private formatSize(bytes: number): string { + if (bytes < 1024) return bytes + " B"; + if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + " KB"; + return (bytes / 1024 / 1024).toFixed(1) + " MB"; + } + + private async downloadAttachment(acc: MailAccount | undefined, mail: MailDetail, filename: string): Promise { + if (!acc) return; + try { + const dir = `MailDesk附件/${acc.name}`; + if (!(await this.app.vault.adapter.exists(dir))) await this.app.vault.createFolder(dir); + const target = `${dir}/${filename}`; + const fullPath = (this.app.vault.adapter as unknown as { getFullPath: (p: string) => string }).getFullPath(target); + await this.plugin.mail.downloadAttachment(acc, mail.folder, mail.uid, filename, fullPath); + new Notice("✓ 已保存到 " + dir); + this.app.vault.trigger("modify"); + } catch (e) { + this.showError("附件下载失败", e); + } + } + + private textButton(parent: HTMLElement, label: string, icon: string, cb: () => void): void { + const b = parent.createEl("button", { cls: "maildesk-text-btn" }); + setIcon(b, icon); + b.appendText(label); + b.onclick = cb; + } + + private async saveAsNote(mail: MailDetail, silent = false): Promise { + const safe = mail.subject.replace(/[\\/:*?"<>|]/g, "-").slice(0, 80) || "邮件"; + const folder = this.plugin.settings.defaultFolder || "INBOX"; + const dateStr = new Date(mail.date).toISOString().slice(0, 10); + const path = `MailDesk邮件/${folder}/${dateStr} ${safe}.md`; + const body = mail.text || this.htmlToText(mail.html); + const content = [ + "---", + `date: ${new Date(mail.date).toISOString()}`, + `from: ${mail.from}`, + `to: ${mail.to}`, + `subject: ${mail.subject}`, + "---", + "", + body, + ].join("\n"); + try { + const parts = path.split("/"); + let cur = ""; + for (let i = 0; i < parts.length - 1; i++) { + cur = cur ? cur + "/" + parts[i] : parts[i]; + if (!(await this.app.vault.adapter.exists(cur))) await this.app.vault.createFolder(cur); + } + const existing = this.app.vault.getAbstractFileByPath(path); + if (existing) { + const alt = `MailDesk邮件/${folder}/${dateStr} ${safe} ${Date.now().toString(36)}.md`; + await this.app.vault.create(alt, content); + if (!silent) new Notice("✓ 已保存为笔记:" + alt); + } else { + await this.app.vault.create(path, content); + if (!silent) new Notice("✓ 已保存为笔记:" + path); + } + } catch (e) { + this.showError("保存失败", e); + } + } + + private htmlToText(html: string): string { + return html + .replace(//gi, "\n") + .replace(/<\/p>/gi, "\n") + .replace(/<[^>]*>/g, " ") + .replace(/ /g, " ") + .replace(/&/g, "&") + .replace(/[ \t]+/g, " ") + .trim(); + } + + private renderEmptyReader(): void { + if (!this.readerEl) return; + this.readerEl.empty(); + const wrap = this.readerEl.createDiv("maildesk-empty-reader"); + const icon = wrap.createDiv("maildesk-empty-icon"); + setIcon(icon, "mail"); + wrap.createSpan({ cls: "maildesk-empty-title", text: "选择一封邮件查看内容" }); + wrap.createSpan({ cls: "maildesk-empty-desc", text: "点击左侧列表中的邮件,即可在这里阅读、回复或转发。" }); + } + + private renderListEmpty(container: HTMLElement, icon: string, title: string, desc: string): void { + const wrap = container.createDiv("maildesk-list-empty"); + const iconEl = wrap.createDiv("maildesk-empty-icon"); + setIcon(iconEl, icon); + wrap.createSpan({ cls: "maildesk-empty-title", text: title }); + wrap.createSpan({ cls: "maildesk-empty-desc", text: desc }); + } + + private toast(message: string): void { + document.querySelector(".maildesk-toast")?.remove(); + const toast = document.body.createDiv("maildesk-toast"); + toast.setText(message); + if (this.toastTimer !== null) window.clearTimeout(this.toastTimer); + this.toastTimer = window.setTimeout(() => toast.remove(), 2200); + } + + private showError(prefix: string, e: unknown): void { + const msg = e instanceof Error ? e.message : String(e); + new Notice(`${prefix}:${msg}`, 8000); + } + + /** 外部触发刷新(收信完成后调用) */ + refresh(): void { + if (!this.contentEl || !this.accountListEl) return; + // 设置面板改了宽度后,同步到视图 + this.applyColumnWidths(); + this.renderAccounts(); + this.renderMailList(); + if (this.selectedMail) { + const acc = this.getAccount(this.selectedMail); + if (acc) this.renderFolders(); + } + } + + private composeNew(): void { + new ComposeModal(this.app, this.plugin, { kind: "new" }).open(); + } + + private async syncAll(btn?: HTMLElement): Promise { + if (btn) btn.addClass("is-spinning"); + try { + // 顶部刷新:收信 + 顺便刷新当前账户的文件夹(静默) + await this.plugin.syncAll(true); + await this.refreshFoldersFromServer(true); + } finally { + if (btn) btn.removeClass("is-spinning"); + } + } + + async onClose(): Promise { + if (this.toastTimer !== null) window.clearTimeout(this.toastTimer); + this.themeObserver?.disconnect(); + this.themeObserver = null; + this.contentEl.empty(); + // 面板关闭后按「是否还有邮件面板可见」决定还原侧栏宽度 + this.plugin.handleMailViewClosed(); + } +} diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..545bd9d --- /dev/null +++ b/styles.css @@ -0,0 +1,987 @@ +/* ========================================================================== + Mail Desk — 样式表 + 设计原则:所有颜色取自 Obsidian 主题变量,深浅主题与自定义主题自动适配。 + 布局:账户栏(窄) + 邮件列表(窄) + 阅读区(flex 占满剩余,最大化)。 + 打开面板时会把左侧栏临时加宽到三栏都放得下;真正窄(<560)时 + 账户栏收起为「账户与文件夹」一屏,列表 / 阅读互斥切换。 + + ⚠ 隔离约定(非常重要): + 1) 本文件所有规则必须带 .maildesk- 前缀,禁止出现 :root / body / html / + .workspace / .workspace-split / .workspace-leaf / .view-content 等全局选择器, + 否则会影响其它插件的边栏样式与宽度。 + 2) 所有 CSS 变量都在本插件自己的作用域内声明(见下方 .maildesk-view 等), + 禁止写到 :root,避免污染主题与其它插件。 + 3) 侧栏宽度只在打开面板时由 JS 写一次内联 width(Obsidian 原生拖拽同一属性), + 不再用 CSS !important 接管——否则边缘拖动会失效甚至拖出异常窗口。 + ========================================================================== */ + +/* 插件内变量:只作用于本插件自己的容器(视图 / 写邮件弹窗 / 确认弹窗) */ +.maildesk-view, +.maildesk-compose, +.maildesk-confirm-modal { + --maildesk-border: var(--background-modifier-border); + --maildesk-border-soft: var(--background-modifier-border-hover, var(--maildesk-border)); +} + +.maildesk-view { + /* 宽度完全由父容器(侧栏 leaf)决定,绝不给父级反向撑宽 */ + box-sizing: border-box; + width: 100%; + max-width: 100%; + min-width: 0; + display: flex; + flex-direction: column; + height: 100%; + font-size: var(--font-ui-small); + overflow: hidden; + background: var(--background-primary); + color: var(--text-normal); +} + +/* ---------------------------------------------------------------- 工具栏 */ +.maildesk-toolbar { + display: flex; + align-items: center; + gap: 8px; + /* Mail Desk 标题左侧不留边距 */ + padding: 6px 10px 6px 0; + border-bottom: 1px solid var(--maildesk-border); + flex: 0 0 auto; + min-height: 38px; +} +.maildesk-toolbar-title { + display: flex; + align-items: center; + gap: 6px; + font-weight: 600; + letter-spacing: .02em; + white-space: nowrap; +} +.maildesk-toolbar-title .maildesk-title-icon { + color: var(--interactive-accent); + display: inline-flex; +} +.maildesk-toolbar-actions { + display: flex; + gap: 2px; + margin-left: auto; + align-items: center; +} +.maildesk-icon-btn { + background: transparent; + border: none; + color: var(--text-muted); + cursor: pointer; + padding: 5px; + border-radius: var(--radius-s); + display: inline-flex; + align-items: center; + justify-content: center; + transition: background .12s ease, color .12s ease, transform .12s ease; + position: relative; +} +.maildesk-icon-btn svg { width: 16px; height: 16px; } +.maildesk-icon-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} +/* 顶部右侧三个按钮:彻底无边框、无背景(含 Obsidian 默认 button 阴影) */ +.maildesk-toolbar-actions .maildesk-icon-btn, +.maildesk-toolbar-actions .maildesk-icon-btn:hover, +.maildesk-toolbar-actions .maildesk-icon-btn.is-active { + background: transparent !important; + border: none !important; + box-shadow: none !important; +} +.maildesk-toolbar-actions .maildesk-icon-btn:hover { color: var(--text-normal); } +.maildesk-icon-btn:active { transform: scale(.92); } +.maildesk-icon-btn.is-active { + color: var(--interactive-accent); + background: var(--background-modifier-hover); +} +.maildesk-icon-btn.is-spinning svg { animation: maildesk-spin 1s linear infinite; } +@keyframes maildesk-spin { to { transform: rotate(360deg); } } + +/* 返回按钮:仅窄栏阅读态显示 */ +.maildesk-back-btn { display: none; margin-right: 2px; } + +/* ------------------------------------------------------------ 搜索框行 */ +.maildesk-searchbar { + display: flex; + flex-wrap: wrap; + justify-content: center; + align-items: center; + gap: 0; + /* 搜索框上边距 = 原来的三倍(6px → 18px);下边距与标签行上边距一致 */ + padding: 18px 10px 12px; + border-bottom: 1px solid var(--maildesk-border); + flex: 0 0 auto; +} +/* 搜索框居中,约占一半宽度 */ +.maildesk-search-input { flex: 0 1 50%; max-width: 50%; min-width: 0; } +.maildesk-search-input input { width: 100%; height: var(--input-height, 30px); } +/* 标签独占一行:上边距 12px(与搜索框下边距一致),下边距 0(searchbar 的 padding-bottom 12px 即内容间距) */ +.maildesk-filter-row { + flex: 0 0 100%; + display: flex; + justify-content: center; + align-items: center; + padding-top: 12px; + position: relative; +} +/* 「设为已读」位于「全选」右侧,默认低调,勾选后高亮 */ +.maildesk-set-read-btn { + background: transparent; + border: 1px solid transparent; + box-shadow: none; + color: var(--text-muted); + cursor: pointer; + font-size: 11px; + padding: 5px 10px; + height: auto; + line-height: 1.2; + border-radius: var(--radius-s); + white-space: nowrap; + display: inline-flex; + align-items: center; + margin-left: 2px; +} +.maildesk-set-read-btn:hover { color: var(--interactive-accent); background: var(--background-modifier-hover); } +.maildesk-set-read-btn.is-ready { + color: var(--interactive-accent); + border-color: var(--interactive-accent); +} +.maildesk-set-read-btn.is-busy { opacity: .55; cursor: default; pointer-events: none; } +/* 「删除」紧随设为已读右侧,危险操作用错误色,勾选后高亮 */ +.maildesk-delete-btn { + background: transparent; + border: 1px solid transparent; + box-shadow: none; + color: var(--text-muted); + cursor: pointer; + font-size: 11px; + padding: 5px 10px; + height: auto; + line-height: 1.2; + border-radius: var(--radius-s); + white-space: nowrap; + display: inline-flex; + align-items: center; + margin-left: 2px; +} +.maildesk-delete-btn:hover { color: var(--text-error); background: var(--background-modifier-hover); } +.maildesk-delete-btn.is-ready { color: var(--text-error); border-color: var(--text-error); } +.maildesk-delete-btn.is-busy { opacity: .55; cursor: default; pointer-events: none; } +/* 「全部/未读」作为紧凑分段控件水平居中,两者中间留 6px 边距 */ +.maildesk-filter-tabs { + display: flex; + align-items: center; + justify-content: center; + gap: 6px; + flex: 0 0 auto; + margin-left: 0; + background: transparent; + border-radius: var(--radius-s); + padding: 0; + box-sizing: border-box; + width: auto; +} +.maildesk-filter-tab { + background: transparent; + border: none; + color: var(--text-muted); + cursor: pointer; + font-size: 11px; + /* 上下边距一致 */ + padding: 5px 10px; + height: auto; + line-height: 1.2; + border-radius: var(--radius-s); + transition: background .12s ease, color .12s ease; + white-space: nowrap; + display: inline-flex; + align-items: center; +} +.maildesk-filter-tab:hover { color: var(--text-normal); } +.maildesk-filter-tab.is-active { + background: var(--background-modifier-hover); + color: var(--text-normal); + box-shadow: 0 1px 2px rgba(0,0,0,.10); +} +.maildesk-filter-tab .maildesk-tab-count { + color: var(--text-faint); + margin-left: 3px; + font-size: 10px; +} + +/* ---------------------------------------------------------------- 三栏 */ +.maildesk-body { + display: flex; + flex: 1 1 auto; + min-width: 0; + min-height: 0; + overflow: hidden; +} +/* 账户 / 文件夹:窄栏,浅灰底与列表区分出层次 */ +.maildesk-sidebar { + width: var(--maildesk-sidebar-w, 132px); + flex: 0 0 var(--maildesk-sidebar-w, 132px); + min-width: 100px; + max-width: 300px; + border-right: 1px solid var(--maildesk-border); + overflow-y: auto; + overflow-x: hidden; + padding: 8px 6px; + background: var(--background-secondary-alt, var(--background-secondary)); +} +/* 邮件列表:窄栏,宽度固定;阅读区占满剩余 */ +.maildesk-list-col { + width: var(--maildesk-list-w, 250px); + flex: 0 0 var(--maildesk-list-w, 250px); + min-width: 180px; + max-width: 520px; + display: flex; + flex-direction: column; + border-right: 1px solid var(--maildesk-border); + overflow: hidden; + background: var(--background-primary); +} +/* 阅读区:占满所有剩余宽度,最大化 */ +.maildesk-reader-col { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + display: flex; + background: var(--background-primary); +} + +/* 拖拽分隔条:8px 更好点中,hover 高亮 */ +.maildesk-splitter { + flex: 0 0 8px; + width: 8px; + cursor: col-resize; + background: transparent; + position: relative; + z-index: 2; + transition: background .12s ease; +} +.maildesk-splitter::after { + content: ""; + position: absolute; + inset: 0 -1px; +} +.maildesk-splitter:hover, +.maildesk-splitter.is-dragging { background: var(--interactive-accent); } +.maildesk-view.is-resizing, +.maildesk-body.is-resizing { cursor: col-resize; user-select: none; } + +/* ------------------------------------------------------------ 栏目标题 */ +.maildesk-col-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 2px 6px 6px; +} +.maildesk-col-title { + font-size: 10px; + text-transform: uppercase; + color: var(--text-faint); + letter-spacing: .08em; + font-weight: 600; +} +.maildesk-col-action { + background: transparent; + border: none; + color: var(--text-faint); + cursor: pointer; + padding: 2px; + display: inline-flex; + border-radius: var(--radius-s); +} +.maildesk-col-action:hover { color: var(--text-normal); background: var(--background-modifier-hover); } + +/* ------------------------------------------------------------ 账户列表 */ +.maildesk-account-row { + display: flex; + align-items: center; + gap: 7px; + padding: 6px 7px; + border-radius: var(--radius-s); + cursor: pointer; + white-space: nowrap; + overflow: hidden; + transition: background .12s ease; + margin-bottom: 2px; +} +.maildesk-account-row:hover { background: var(--background-modifier-hover); } +.maildesk-account-row.is-active { + background: var(--background-modifier-selected); + color: var(--text-normal); + font-weight: 600; + position: relative; +} +/* 选中账户:左侧强调条 + 加粗文字,与未选中态明显区分 */ +.maildesk-account-row.is-active::before { + content: ""; + position: absolute; + left: 0; top: 3px; bottom: 3px; + width: 3px; + border-radius: 2px; + background: var(--interactive-accent); +} +.maildesk-account-row.is-active .maildesk-account-name { font-weight: 600; color: var(--text-normal); } +.maildesk-account-dot { + flex: 0 0 auto; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-faint); + opacity: .9; +} +.maildesk-account-row.is-active .maildesk-account-dot { background: var(--interactive-accent); opacity: 1; } +.maildesk-account-name { + flex: 1 1 auto; + overflow: hidden; + text-overflow: ellipsis; + font-size: 12px; +} +.maildesk-account-email { + font-size: 10px; + color: var(--text-faint); + overflow: hidden; + text-overflow: ellipsis; +} +.maildesk-account-unread { + background: var(--interactive-accent); + color: var(--text-on-accent); + font-size: 10px; + font-weight: 600; + min-width: 18px; + text-align: center; + border-radius: 9px; + padding: 1px 5px; + flex: 0 0 auto; +} + +/* ------------------------------------------------------------ 文件夹列表 */ +.maildesk-folder-list { + margin-top: 10px; + border-top: 1px solid var(--maildesk-border); + padding-top: 8px; +} +.maildesk-folder-row { + display: flex; + align-items: center; + gap: 7px; + padding: 5px 7px; + border-radius: var(--radius-s); + cursor: pointer; + white-space: nowrap; + overflow: hidden; + font-size: 12px; + color: var(--text-muted); + transition: background .12s ease, color .12s ease; + margin-bottom: 2px; +} +.maildesk-folder-row:hover { background: var(--background-modifier-hover); color: var(--text-normal); } +.maildesk-folder-row.is-active { + background: var(--background-modifier-selected); + color: var(--text-normal); + font-weight: 500; +} +.maildesk-folder-icon { flex: 0 0 auto; display: inline-flex; color: var(--text-faint); } +.maildesk-folder-row.is-active .maildesk-folder-icon { color: var(--interactive-accent); } +.maildesk-folder-name { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; } +.maildesk-folder-count { font-size: 10px; color: var(--text-faint); flex: 0 0 auto; } + +/* -------------------------------------------------------- 列表上方工具条 */ +/* 「选择」位于「全选」左侧,进入手动选择态(显示复选框但不预选),默认低调、选中态高亮 */ +.maildesk-select-mode-btn { + background: transparent; + border: 1px solid transparent; + box-shadow: none; + color: var(--text-muted); + cursor: pointer; + font-size: 11px; + padding: 5px 8px; + height: auto; + line-height: 1.2; + border-radius: var(--radius-s); + white-space: nowrap; + display: inline-flex; + align-items: center; + margin-left: 8px; +} +.maildesk-select-mode-btn:hover { color: var(--interactive-accent); background: var(--background-modifier-hover); } +.maildesk-select-mode-btn.is-active { color: var(--interactive-accent); font-weight: 600; } +/* 「全选」位于过滤行内、设为已读左侧,和标签同高,左侧留间隔与筛选标签区分 */ +.maildesk-select-all-btn { + background: transparent; + border: 1px solid transparent; + box-shadow: none; + color: var(--text-muted); + cursor: pointer; + font-size: 11px; + padding: 5px 8px; + height: auto; + line-height: 1.2; + border-radius: var(--radius-s); + white-space: nowrap; + display: inline-flex; + align-items: center; + margin-left: 8px; +} +.maildesk-select-all-btn:hover { color: var(--interactive-accent); background: var(--background-modifier-hover); } +.maildesk-select-all-btn.is-active { color: var(--interactive-accent); font-weight: 600; } + +/* ------------------------------------------------------------ 邮件列表 */ +.maildesk-mail-list { + flex: 1 1 auto; + overflow-y: auto; + overflow-x: hidden; +} +.maildesk-mail-row { + padding: 9px 11px 9px 14px; + border-bottom: 1px solid var(--maildesk-border); + cursor: pointer; + position: relative; + transition: background .1s ease; +} +.maildesk-mail-row:hover { background: var(--background-modifier-hover); } +/* 未读行不要 hover 效果(选中/勾选态仍保留) */ +.maildesk-mail-row.is-unread:hover:not(.is-selected):not(.is-checked) { background: transparent; } +.maildesk-mail-row.is-selected { background: var(--background-modifier-selected); } +.maildesk-mail-row.is-selected::before { + content: ""; + position: absolute; + left: 0; top: 0; bottom: 0; + width: 3px; + background: var(--interactive-accent); +} +/* 多选勾选态:背景高亮 + 左侧强调条 */ +.maildesk-mail-row.is-checked, +.maildesk-mail-row.is-unread:hover.is-checked:not(.is-selected) { background: var(--background-modifier-selected); } +.maildesk-mail-row.is-checked::before { + content: ""; + position: absolute; + left: 0; top: 0; bottom: 0; + width: 3px; + background: var(--text-success, var(--interactive-accent)); +} +.maildesk-mail-row-top { + display: flex; + justify-content: space-between; + gap: 8px; + align-items: center; +} +/* 多选框:默认隐藏,点「全选」进入选择态后才在邮件标题左侧出现 */ +.maildesk-mail-check { + display: none; + flex: 0 0 auto; + width: 14px; + height: 14px; + margin: 0; + accent-color: var(--interactive-accent); + cursor: pointer; +} +.maildesk-list-col.is-selecting .maildesk-mail-check { display: block; } +.maildesk-mail-from { + font-size: 12px; + font-weight: 400; + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1 1 auto; +} +.maildesk-mail-row.is-unread .maildesk-mail-from { font-weight: 600; color: var(--text-normal); } +.maildesk-mail-date { font-size: 10px; color: var(--text-faint); flex: 0 0 auto; } +.maildesk-mail-row.is-unread .maildesk-mail-date { color: var(--text-muted); } +.maildesk-mail-subject { + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-top: 3px; + color: var(--text-normal); +} +.maildesk-mail-row.is-unread .maildesk-mail-subject { font-weight: 600; } +.maildesk-mail-snippet { + font-size: 11px; + color: var(--text-faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-top: 2px; +} +.maildesk-mail-row-foot { + display: flex; + align-items: center; + justify-content: flex-end; + min-height: 14px; + margin-top: 3px; + gap: 6px; +} +.maildesk-mail-att { display: inline-flex; align-items: center; gap: 2px; font-size: 10px; color: var(--text-muted); } +.maildesk-unread-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--interactive-accent); + flex: 0 0 auto; +} + +/* ------------------------------------------------------------ 阅读窗格 */ +.maildesk-reader { + flex: 1 1 auto; + overflow-y: auto; + padding: 0 20px 24px; + min-width: 0; +} +.maildesk-reader-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + padding: 10px 0; + border-bottom: 1px solid var(--maildesk-border); + margin-bottom: 16px; + position: sticky; + top: 0; + background: var(--background-primary); + z-index: 1; +} +/* 左组(回复/回复全部/转发)靠左,右组(存为笔记/设为已读/删除)靠右 */ +.maildesk-reader-bar-left { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} +.maildesk-reader-bar-right { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-left: auto; + justify-content: flex-end; +} +.maildesk-text-btn { + background: var(--background-modifier-form-field); + border: 1px solid var(--maildesk-border); + color: var(--text-normal); + border-radius: var(--radius-s); + padding: 4px 11px; + font-size: 11px; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 5px; + transition: background .12s ease, border-color .12s ease; +} +.maildesk-text-btn:hover { background: var(--background-modifier-hover); border-color: var(--interactive-accent); } +.maildesk-text-btn:active { transform: translateY(1px); } + +.maildesk-reader-header { margin-bottom: 16px; } +.maildesk-reader-header h2 { + margin: 0 0 12px; + font-size: 19px; + line-height: 1.4; + font-weight: 600; +} +.maildesk-reader-meta { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 11px; + color: var(--text-muted); +} +.maildesk-reader-meta .maildesk-meta-avatar { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border-radius: 50%; + background: var(--interactive-accent); + color: var(--text-on-accent); + font-size: 12px; + font-weight: 600; + flex: 0 0 auto; +} +.maildesk-reader-meta-row { display: flex; align-items: center; gap: 9px; } +.maildesk-reader-meta-main { display: flex; flex-direction: column; gap: 1px; } +.maildesk-meta-name { color: var(--text-normal); font-weight: 500; font-size: 12px; } +.maildesk-meta-addr { color: var(--text-faint); font-size: 10px; } +.maildesk-meta-date { margin-left: auto; color: var(--text-faint); font-size: 10px; } + +/* 附件区 */ +.maildesk-reader-attachments { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; + padding: 12px 0; + border-top: 1px solid var(--maildesk-border); + border-bottom: 1px solid var(--maildesk-border); + margin-bottom: 16px; +} +.maildesk-att-label { font-size: 11px; color: var(--text-muted); display: inline-flex; align-items: center; gap: 4px; } +.maildesk-att-chip { + background: var(--background-modifier-form-field); + border: 1px solid var(--maildesk-border); + border-radius: 16px; + padding: 4px 11px; + font-size: 11px; + cursor: pointer; + color: var(--text-normal); + display: inline-flex; + align-items: center; + gap: 5px; + transition: background .12s ease, border-color .12s ease; +} +.maildesk-att-chip:hover { background: var(--background-modifier-hover); border-color: var(--interactive-accent); } + +/* 正文容器:正文 iframe 自己按主题着色(见 view.ts buildMailHtml),这里不加滤镜 */ +.maildesk-reader-content { + border: 1px solid var(--maildesk-border); + border-radius: var(--radius-s); + overflow: hidden; + background: var(--background-primary); +} +.maildesk-mail-iframe { + width: 100%; + min-height: 420px; + border: none; + display: block; +} +.maildesk-mail-text { + white-space: pre-wrap; + word-break: break-word; + font-family: var(--font-text); + line-height: 1.7; + font-size: 13px; + padding: 16px; + margin: 0; + color: var(--text-normal); +} + +/* ------------------------------------------------------------ 空状态 / 加载 */ +.maildesk-empty-hint, +.maildesk-empty-reader, +.maildesk-loading { color: var(--text-faint); font-size: 12px; } +.maildesk-empty-reader { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100%; + gap: 12px; + text-align: center; +} +.maildesk-empty-icon { + display: inline-flex; + width: 48px; + height: 48px; + align-items: center; + justify-content: center; + border-radius: 50%; + background: var(--background-modifier-hover); + color: var(--text-faint); +} +.maildesk-empty-icon svg { width: 24px; height: 24px; } +.maildesk-empty-title { color: var(--text-muted); font-size: 13px; } +.maildesk-empty-desc { color: var(--text-faint); font-size: 11px; max-width: 220px; line-height: 1.5; } +.maildesk-loading { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 30px 10px; } +.maildesk-spinner { + width: 14px; + height: 14px; + border: 2px solid var(--background-modifier-border); + border-top-color: var(--interactive-accent); + border-radius: 50%; + animation: maildesk-spin .7s linear infinite; +} +.maildesk-list-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 40px 20px; + gap: 10px; + text-align: center; + color: var(--text-faint); +} + +/* ------------------------------------------------------------ 写邮件 */ +.maildesk-compose .setting-item { border: none; padding: 6px 0; } +.maildesk-compose h2 { margin-bottom: 14px; } +.maildesk-compose-body-wrap { margin: 10px 0; display: flex; flex-direction: column; gap: 4px; } +.maildesk-compose-label { font-size: 12px; color: var(--text-muted); } +.maildesk-compose-body { + width: 100%; + min-height: 240px; + resize: vertical; + background: var(--background-modifier-form-field); + color: var(--text-normal); + border: 1px solid var(--maildesk-border); + border-radius: var(--radius-s); + padding: 10px; + font-family: var(--font-text); + line-height: 1.6; + font-size: 13px; + transition: border-color .12s ease; +} +.maildesk-compose-body:focus { outline: none; border-color: var(--interactive-accent); } +.maildesk-compose-attachments { margin: 8px 0; } +.maildesk-att-row { + display: flex; + justify-content: space-between; + align-items: center; + padding: 5px 8px; + font-size: 11px; + color: var(--text-muted); + background: var(--background-modifier-form-field); + border: 1px solid var(--maildesk-border); + border-radius: var(--radius-s); + margin-bottom: 4px; +} +.maildesk-att-remove { + background: transparent; + border: none; + color: var(--text-faint); + cursor: pointer; + font-size: 15px; + line-height: 1; +} +.maildesk-att-remove:hover { color: var(--text-error); } +.maildesk-compose-footer { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 14px; + padding-top: 12px; + border-top: 1px solid var(--maildesk-border); +} +.maildesk-compose-footer button { min-width: 72px; } + +/* ------------------------------------------------------------ 确认弹窗 */ +.maildesk-confirm-modal .modal-content { text-align: center; padding: 8px 0; } +.maildesk-confirm-title { font-size: 15px; font-weight: 600; margin-bottom: 8px; } +.maildesk-confirm-desc { color: var(--text-muted); font-size: 12px; margin-bottom: 18px; line-height: 1.5; } +.maildesk-confirm-actions { display: flex; justify-content: center; gap: 10px; } +.maildesk-confirm-actions button { min-width: 80px; } +.maildesk-btn-danger { background: var(--text-error) !important; color: #fff !important; } + +/* ------------------------------------------------------------ 设置页 */ +.maildesk-setting-hint { color: var(--text-muted); font-size: 12px; line-height: 1.6; } +.maildesk-secret-row { padding-left: 18px; } +.maildesk-setting-section-title { margin-top: 20px; margin-bottom: 4px; color: var(--text-normal); } +/* 分区标题:去掉左边距 */ +.maildesk-section-heading { margin-left: 0 !important; padding-left: 0 !important; } +.maildesk-account-card { border: 1px solid var(--maildesk-border); border-radius: var(--radius-s); padding: 6px 10px; margin-bottom: 8px; } +.maildesk-setting-status-ok { color: var(--text-success); } +.maildesk-setting-status-err { color: var(--text-error); } +/* 添加邮箱账户按钮:真正左右居中(隐藏空的信息列,占满整行居中) */ +.maildesk-add-account.setting-item { justify-content: center !important; } +.maildesk-add-account .setting-item-info { display: none !important; } +.maildesk-add-account .setting-item-control { flex: 1 1 auto !important; justify-content: center !important; } + +/* ------------------------------------------------------------ 角标 / 状态栏 */ +.maildesk-badge { + position: absolute; + top: 1px; + right: 1px; + min-width: 16px; + height: 16px; + line-height: 16px; + text-align: center; + font-size: 10px; + font-weight: 600; + background: var(--text-error); + color: #fff; + border-radius: 8px; + padding: 0 4px; + pointer-events: none; + box-shadow: 0 0 0 2px var(--background-primary); +} +.maildesk-statusbar { cursor: pointer; transition: color .12s ease; } +.maildesk-statusbar:hover { color: var(--text-normal); } +.maildesk-statusbar-has-unread { color: var(--interactive-accent); font-weight: 500; } + +/* ------------------------------------------------------------ Toast */ +.maildesk-toast { + position: fixed; + bottom: 32px; + left: 50%; + transform: translateX(-50%); + background: var(--background-primary); + border: 1px solid var(--maildesk-border); + border-radius: var(--radius-s); + padding: 8px 16px; + font-size: 12px; + color: var(--text-normal); + box-shadow: 0 4px 16px rgba(0,0,0,.2); + z-index: 1000; + pointer-events: none; + animation: maildesk-toast-in .2s ease; +} +@keyframes maildesk-toast-in { + from { opacity: 0; transform: translate(-50%, 8px); } + to { opacity: 1; transform: translate(-50%, 0); } +} + +/* ========================================================================== + 窄屏布局(<560):账户栏 / 邮件列表 / 阅读 三屏互斥 + —— 默认显示邮件列表;工具栏的「账户」按钮切到账户与文件夹屏, + 选完账户或文件夹后自动回到列表;点邮件进入阅读,返回键回列表。 + ========================================================================== */ +.maildesk-view.is-narrow .maildesk-sidebar, +.maildesk-view.is-narrow .maildesk-splitter-sidebar { display: none; } +.maildesk-view.is-narrow .maildesk-list-col { + flex: 1 1 auto; + width: 100%; + max-width: none; +} +.maildesk-view.is-narrow .maildesk-splitter-list { display: none; } +.maildesk-view.is-narrow .maildesk-reader-col { display: none; } +.maildesk-view.is-narrow.reader-open .maildesk-list-col { display: none; } +.maildesk-view.is-narrow.reader-open .maildesk-reader-col { display: flex; } +.maildesk-view.is-narrow .maildesk-back-btn { display: inline-flex; } +.maildesk-view.is-narrow .maildesk-reader { padding: 0 12px 20px; } +.maildesk-view.is-narrow .maildesk-reader-header h2 { font-size: 16px; } + +/* 「账户与文件夹」按钮:只在窄栏出现,显示当前账户名 */ +.maildesk-accounts-btn { display: none; } +.maildesk-view.is-narrow .maildesk-accounts-btn { + display: inline-flex; + gap: 4px; + padding: 4px 6px; + max-width: 50%; + flex: 0 1 auto; + min-width: 0; +} +.maildesk-accounts-btn-label { + font-size: 11px; + max-width: 96px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-muted); +} +/* 窄栏工具栏空间有限:让位给账户按钮,隐藏面板标题(侧栏标签本身就是名称) */ +.maildesk-view.is-narrow .maildesk-toolbar-title { display: none; } +.maildesk-accounts-btn.is-active .maildesk-accounts-btn-label, +.maildesk-accounts-btn:hover .maildesk-accounts-btn-label { color: var(--text-normal); } + +/* 窄栏 · 账户屏:整屏显示账户与文件夹,隐藏列表/阅读 */ +.maildesk-view.is-narrow.show-accounts .maildesk-sidebar { + display: block; + flex: 1 1 auto; + width: 100%; + max-width: none; + min-width: 0; + border-right: none; + /* 账户屏常驻滚动到底部也留点呼吸空间 */ + padding: 8px 8px 14px; +} +.maildesk-view.is-narrow.show-accounts .maildesk-list-col, +.maildesk-view.is-narrow.show-accounts .maildesk-reader-col { display: none; } +.maildesk-view.is-narrow.show-accounts .maildesk-splitter { display: none; } + +/* ========================================================================== + 细节打磨:滚动条 / 焦点可见性 / 搜索框聚焦态(增量增强,不改布局) + ========================================================================== */ + +/* 细滚动条:跟随主题,避免侧栏滚动条粗重突兀 */ +.maildesk-sidebar, +.maildesk-mail-list, +.maildesk-reader, +.maildesk-compose-body { + scrollbar-width: thin; + scrollbar-color: var(--background-modifier-border) transparent; +} +.maildesk-sidebar::-webkit-scrollbar, +.maildesk-mail-list::-webkit-scrollbar, +.maildesk-reader::-webkit-scrollbar, +.maildesk-compose-body::-webkit-scrollbar { width: 8px; height: 8px; } +.maildesk-sidebar::-webkit-scrollbar-thumb, +.maildesk-mail-list::-webkit-scrollbar-thumb, +.maildesk-reader::-webkit-scrollbar-thumb, +.maildesk-compose-body::-webkit-scrollbar-thumb { + background: var(--background-modifier-border); + border-radius: 4px; + border: 2px solid transparent; + background-clip: padding-box; +} +.maildesk-sidebar::-webkit-scrollbar-thumb:hover, +.maildesk-mail-list::-webkit-scrollbar-thumb:hover, +.maildesk-reader::-webkit-scrollbar-thumb:hover { background: var(--background-modifier-border-hover, var(--text-faint)); background-clip: padding-box; } +.maildesk-sidebar::-webkit-scrollbar-track, +.maildesk-mail-list::-webkit-scrollbar-track, +.maildesk-reader::-webkit-scrollbar-track { background: transparent; } + +/* 键盘焦点可见:只用 :focus-visible,鼠标点击不显示轮廓 */ +.maildesk-view :is(button, input, textarea, [tabindex]):focus-visible { + outline: 2px solid var(--interactive-accent); + outline-offset: 1px; +} + +/* 搜索框聚焦态:边框强调,输入更聚焦 */ +.maildesk-search-input input { + background: var(--background-modifier-form-field); + border: 1px solid var(--maildesk-border); + border-radius: var(--radius-s); + padding: 0 8px; + box-sizing: border-box; + transition: border-color .12s ease, box-shadow .12s ease; +} +.maildesk-search-input input:focus { + outline: none; + border-color: var(--interactive-accent); + box-shadow: 0 0 0 2px var(--background-modifier-hover); +} +.maildesk-search-input input::placeholder { color: var(--text-faint); } + +/* 未读行左侧柔和标记(比选中条更轻,避免喧宾夺主) */ +.maildesk-mail-row.is-unread:not(.is-selected)::before { + content: ""; + position: absolute; + left: 0; top: 0; bottom: 0; + width: 3px; + background: var(--interactive-accent); + opacity: .35; +} + +/* 文本选中色跟随主题强调色 */ +.maildesk-view ::selection { background: var(--background-modifier-selected); } + +/* 减少动画偏好 */ +@media (prefers-reduced-motion: reduce) { + .maildesk-view * { animation: none !important; transition: none !important; } +} + +/* ========================================================================== + 隔离兜底:确保本插件不会把自身宽度「反向」撑给容器 + (侧栏宽度只由用户拖动 / Obsidian 自身决定,插件只做自适应) + ========================================================================== */ +.maildesk-view, +.maildesk-view > *, +.maildesk-body > * { + box-sizing: border-box; +} +.maildesk-view > * { + min-width: 0; + max-width: 100%; +} +.maildesk-reader, +.maildesk-reader-content, +.maildesk-mail-iframe { + max-width: 100%; +} + +/* ========================================================================== + 注意:本文件不再包含任何命中 .workspace-split 的规则。 + 侧栏宽度由 JS 写一次内联 width 实现(与 Obsidian 自身拖拽同一个属性), + 因此拖拽边缘调宽永远有效,也不会出现「拖出新标签页 / 卡死」的问题。 + ========================================================================== */