// 自定义通知弹窗(右下角 toast):无边框、置顶、不抢焦点、按级别配色。 // 替代系统原生通知(原生样式跟随 Windows 主题,深色模式下发黑、不可控)。 "use strict"; const { makeLogger } = require("./logger"); const logger = makeLogger("notify-toast"); const W = 380, H = 132, GAP = 10, MARGIN = 16, TTL = 9000; // 同屏最多几条(超出后关掉最早的那条,避免糊满屏幕) const MAX_VISIBLE = 4; // 当前在显示的窗口,自下而上排列:末尾 = 最新(最靠下) const _stack = []; // 重新排布:最新的一条贴着屏幕右下角,其余依次往上叠。 // 关键点是"有窗口消失时也要重排",否则会留下空洞、新通知从半空中冒出来。 function layout() { let wa; try { wa = require("electron").screen.getPrimaryDisplay().workArea; } catch (e) { return; // 非 Electron 环境 } const x = Math.round(wa.x + wa.width - W - MARGIN); let bottom = wa.y + wa.height - MARGIN; for (let i = _stack.length - 1; i >= 0; i--) { const y = Math.round(bottom - H); const win = _stack[i].win; try { if (!win.isDestroyed()) win.setPosition(x, y); } catch (e) { /* 窗口正在销毁:忽略 */ } bottom = y - GAP; } } // 从栈里摘掉并让剩下的整体下沉(补上空位) function removeFromStack(win) { const i = _stack.findIndex((it) => it.win === win); if (i < 0) return; _stack.splice(i, 1); layout(); } function closeToast(win) { try { if (!win.isDestroyed()) win.destroy(); } catch (e) { /* 忽略 */ } } function levelColor(level) { return { info: "#2f5cf0", warning: "#d97706", important: "#d6453d" }[level] || "#2f5cf0"; } function levelLabel(level) { return { info: "通知", warning: "提醒", important: "重要" }[level] || "通知"; } function esc(s) { return String(s || "") .replace(/&/g, "&").replace(//g, ">") .replace(/"/g, """); } function buildHTML(title, body, level) { const color = levelColor(level); const label = levelLabel(level); return `
${label} ✕
${esc(title)}
${esc(body)}
`; } function show(title, body, level) { try { const { BrowserWindow, screen } = require("electron"); const wa = screen.getPrimaryDisplay().workArea; // 超过上限:先关掉最早的一条(它的 closed 会把自己从栈里摘掉) while (_stack.length >= MAX_VISIBLE) { closeToast(_stack[0].win); if (_stack.length >= MAX_VISIBLE) _stack.shift(); // 兜底:closed 没触发也不能死循环 } const win = new BrowserWindow({ width: W, height: H, x: Math.round(wa.x + wa.width - W - MARGIN), y: Math.round(wa.y + wa.height - H - MARGIN), frame: false, transparent: true, resizable: false, movable: false, alwaysOnTop: true, skipTaskbar: true, hasShadow: false, show: false, focusable: false, backgroundColor: "#00000000", webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true }, }); win.setAlwaysOnTop(true, "pop-up-menu"); _stack.push({ win }); layout(); // 先摆好位置再显示,避免出现"闪一下再跳" win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML(title, body, level))); win.once("ready-to-show", () => { try { win.showInactive(); } catch (e) { win.show(); } }); const t = setTimeout(() => closeToast(win), TTL); win.on("closed", () => { clearTimeout(t); removeFromStack(win); // 摘掉后剩余的立刻下沉,补上空位 }); return true; } catch (e) { logger.warning(`自定义通知弹窗失败:${e.message}`); return false; } } module.exports = { show };