示例工程 31-notifications-taskbar

31-notifications-taskbar/app/main/index.ts

typescript · 11 KB

import {
  app,
  BrowserWindow,
  ipcMain,
  Notification,
  type NotificationConstructorOptions,
} from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  assertBadgeReq,
  assertPreviewReq,
  assertProgressReq,
  assertSendReq,
  CH,
  type Capabilities,
  type NotifyLog,
  type NotifyPayload,
  type NotifySnapshot,
  type ProgressMode,
  type Redacted,
} from "../shared/ipc";
import { redactPayload } from "../shared/redact";

app.setName("Notify Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
  isSmoke || isShots
    ? path.join(
        os.tmpdir(),
        `notify-lab-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

let win: BrowserWindow | null = null;
let badge = "";
let progress = -1;
let mode: ProgressMode = "none";
let lastPayload: Redacted | null = null;
let lastClicked = "";
let log: NotifyLog[] = [];
let liveNotification: Notification | null = null;

const supported = (): boolean => Notification.isSupported();

function capabilities(): Capabilities {
  return {
    notifications: supported(),
    actions: process.platform === "darwin",
    badge: process.platform === "darwin" || process.platform === "linux",
    progress: process.platform === "win32" || process.platform === "linux",
    overlay: process.platform === "win32",
    bounce:
      process.platform === "darwin" ||
      process.platform === "win32" ||
      process.platform === "linux",
  };
}

function addLog(entry: Omit<NotifyLog, "at">): void {
  log = [{ at: Date.now(), ...entry }, ...log].slice(0, 30);
}

function focusWindow(): void {
  if (!win || win.isDestroyed()) return;
  win.show();
  win.focus();
}

function applyBadge(): void {
  if (process.platform === "darwin") {
    app.dock?.setBadge(badge);
  } else if (process.platform === "linux") {
    const count = Number(badge);
    app.setBadgeCount(Number.isFinite(count) ? count : 0);
  }
}

function applyProgress(): void {
  if (!win || win.isDestroyed()) return;
  if (process.platform === "darwin") return;
  win.setProgressBar(progress, { mode });
}

function applyBounce(): void {
  if (process.platform === "darwin") {
    app.dock?.bounce("informational");
  } else if (win && !win.isDestroyed()) {
    win.flashFrame(true);
  }
}

function snapshot(): NotifySnapshot {
  return {
    platform: process.platform,
    capabilities: capabilities(),
    supported: supported(),
    lastPayload,
    badge,
    progress,
    mode,
    lastClicked,
    log: [...log],
  };
}

function broadcast(): void {
  const state = snapshot();
  for (const window of BrowserWindow.getAllWindows()) {
    if (!window.isDestroyed()) window.webContents.send(CH.changed, state);
  }
}

function handleClick(source: string): void {
  if (!lastPayload) return;
  focusWindow();
  lastClicked = lastPayload.title;
  addLog({ kind: "click", text: `${source}点击:${lastPayload.title}` });
  broadcast();
}

function sendNotification(raw: NotifyPayload): NotifySnapshot {
  const redacted = redactPayload(raw.title, raw.body);
  lastPayload = redacted;
  addLog({
    kind: "show",
    text: isSmoke ? `生成通知(dry-run):${redacted.title}` : redacted.title,
  });

  if (!isSmoke && supported()) {
    const options: NotificationConstructorOptions = {
      title: redacted.title,
      body: redacted.body,
      silent: raw.silent,
      urgency: raw.urgency,
    };
    if (process.platform === "darwin") {
      options.actions = [
        { type: "button", text: "打开" },
        { type: "button", text: "稍后" },
      ];
    }
    const notification = new Notification(options);
    liveNotification = notification;
    notification.on("click", () => handleClick("通知"));
    notification.on("action", () => handleClick("通知动作"));
    notification.on("close", () => {
      addLog({ kind: "close", text: `通知关闭:${redacted.title}` });
      broadcast();
    });
    notification.on("failed", (_event, error) => {
      addLog({ kind: "failed", text: `通知失败:${error}` });
      broadcast();
    });
    notification.show();
  }

  broadcast();
  return snapshot();
}

function resolvePreload(): string {
  const candidates = [
    path.join(__dirname, "preload.cjs"),
    path.join(__dirname, "../preload/index.cjs"),
    path.join(__dirname, "preload.js"),
  ];
  return (
    candidates.find((candidate) => fsSync.existsSync(candidate)) ??
    candidates[0] ??
    ""
  );
}

function createWindow(): BrowserWindow {
  const window = new BrowserWindow({
    width: 1100,
    height: 860,
    show: false,
    title: "通知与任务栏工作台",
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  window.once("ready-to-show", () => window.show());
  window.on("focus", broadcast);
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void window.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  win = window;
  return window;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await window.webContents.executeJavaScript(code)) as T;
    } catch (error) {
      lastError = error;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(window: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        window,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  platform: string;
  supported: boolean;
  previewTitle: string;
  previewBody: string;
  hits: string[];
  showLogged: boolean;
  clicked: string;
  badge: string;
  progress: number;
  bounceLogged: boolean;
  cleared: boolean;
  logAfterClear: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(500);
    await waitForRenderer(window);
    const result = await evalRenderer<SmokeResult>(window, "window.__smoke()");
    const dockBadge = process.platform === "darwin" ? app.dock?.getBadge() : "";
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.supported &&
          result.previewTitle.includes("<user>") &&
          result.previewBody.includes("<email>") &&
          result.previewBody.includes("sk-***") &&
          result.previewBody.includes("Bearer ***") &&
          result.hits.length >= 4 &&
          result.showLogged &&
          result.clicked.length > 0 &&
          result.badge === "3" &&
          result.progress === 0.5 &&
          result.bounceLogged &&
          result.cleared &&
          result.logAfterClear === 0 &&
          dockBadge === "3",
        dockBadge,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  window: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await window.webContents.capturePage();
  if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
  const png = image.toPNG();
  fsSync.writeFileSync(path.join(dir, file), png);
  fsSync.writeFileSync(path.join(dir, "raw", file), png);
}

async function runShots(window: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/31-notifications-taskbar",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(500);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("compose")`);
    await delay(400);
    await capture(window, dir, "31-01-compose.png");
    await evalRenderer(window, `window.__prepareShots("sent")`);
    await delay(500);
    await capture(window, dir, "31-02-sent.png");
    await evalRenderer(window, `window.__prepareShots("dock")`);
    await delay(400);
    await capture(window, dir, "31-03-dock.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.get, () => snapshot());

ipcMain.handle(CH.preview, (_event, raw: unknown) => {
  try {
    assertPreviewReq(raw);
    return redactPayload(raw.title, raw.body);
  } catch {
    throw new Error("NOTIFY_PREVIEW_FAILED");
  }
});

ipcMain.handle(CH.send, (_event, raw: unknown) => {
  try {
    assertSendReq(raw);
    return sendNotification(raw);
  } catch {
    throw new Error("NOTIFY_SEND_FAILED");
  }
});

ipcMain.handle(CH.simulateClick, () => {
  handleClick("模拟");
  return snapshot();
});

ipcMain.handle(CH.setBadge, (_event, raw: unknown) => {
  try {
    assertBadgeReq(raw);
    badge = raw.text;
    applyBadge();
    addLog({ kind: "badge", text: badge ? `徽标:${badge}` : "清除徽标" });
    broadcast();
    return snapshot();
  } catch {
    throw new Error("NOTIFY_BADGE_FAILED");
  }
});

ipcMain.handle(CH.setProgress, (_event, raw: unknown) => {
  try {
    assertProgressReq(raw);
    progress = raw.value;
    mode = raw.mode;
    applyProgress();
    addLog({
      kind: "progress",
      text:
        progress < 0
          ? "清除进度"
          : `进度:${Math.round(progress * 100)}%(${mode})`,
    });
    broadcast();
    return snapshot();
  } catch {
    throw new Error("NOTIFY_PROGRESS_FAILED");
  }
});

ipcMain.handle(CH.bounce, () => {
  applyBounce();
  addLog({ kind: "bounce", text: "请求注意" });
  broadcast();
  return snapshot();
});

ipcMain.handle(CH.clear, () => {
  badge = "";
  progress = -1;
  mode = "none";
  lastPayload = null;
  lastClicked = "";
  log = [];
  liveNotification?.close();
  liveNotification = null;
  applyBadge();
  applyProgress();
  broadcast();
  return snapshot();
});

app.whenReady().then(() => {
  const window = createWindow();
  broadcast();
  if (isSmoke) {
    void runSmoke(window);
  } else if (isShots) {
    void runShots(window);
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    } else {
      focusWindow();
    }
  });
});

app.on("will-quit", () => {
  liveNotification?.close();
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (!isSmoke && !isShots && process.platform !== "darwin") app.quit();
});