// --------------------------------------------------------------------------- // 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} 封邮件标为已读(仅本地)`); } }