示例工程 11-main-process-services

11-main-process-services/app/src/renderer.ts

typescript · 12 KB

import "./styles.css";
import type { Envelope, NoteMeta, NoteRead, PickedFile } from "../shared/ipc";

type TabId = "catalog" | "notes" | "shell";

type ShellResult = {
  allowed?: Envelope<{ url: string; dryRun: boolean }>;
  blocked?: Envelope<{ url: string; dryRun: boolean }>;
};

declare global {
  interface Window {
    api: {
      listNotes(): Promise<Envelope<NoteMeta[]>>;
      readNote(id: string): Promise<Envelope<NoteRead>>;
      writeNote(id: string, content: string): Promise<Envelope<NoteMeta>>;
      removeNote(id: string): Promise<Envelope<null>>;
      resetNotes(): Promise<Envelope<null>>;
      openUrl(url: string): Promise<Envelope<{ url: string; dryRun: boolean }>>;
      pickFile(): Promise<Envelope<PickedFile | null>>;
    };
    __setTab?: (tab: TabId) => void;
    __snapshot?: () => unknown;
    __smoke?: () => Promise<unknown>;
  }
}

const state: {
  tab: TabId;
  notes: NoteMeta[];
  content: string;
  noteId: string;
  shellUrl: string;
  response: unknown;
  shellResult: ShellResult | null;
  picked: PickedFile | null;
  busy: boolean;
} = {
  tab: "catalog",
  notes: [],
  content: "服务层把文件读写、shell 与 dialog 从 IPC 里拆出来。",
  noteId: "welcome",
  shellUrl: "https://example.com/docs",
  response: null,
  shellResult: null,
  picked: null,
  busy: false,
};

const tabs: Array<{ id: TabId; label: string }> = [
  { id: "catalog", label: "服务目录" },
  { id: "notes", label: "笔记服务" },
  { id: "shell", label: "Shell 与 Dialog" },
];

const services = [
  {
    name: "notes-service",
    deps: "fs/promises · path · crypto",
    methods: [
      "list()",
      "read(id)",
      "write(id, content)",
      "remove(id)",
      "reset()",
    ],
    note: "原子写:临时文件 + rename;id 用正则限制;单文件 64KB 上限。",
  },
  {
    name: "shell-service",
    deps: "openExternal(注入)",
    methods: ["open(url)"],
    note: "只允许 https + host 白名单;dryRun 时不真的打开浏览器。",
  },
  {
    name: "dialog-service",
    deps: "showOpenDialog(注入)",
    methods: ["pick()"],
    note: "只接受 .md / .txt;取消返回 null,不抛异常。",
  },
];

function escapeHtml(value: string): string {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function json(value: unknown): string {
  return escapeHtml(JSON.stringify(value, null, 2));
}

function time(at: number): string {
  return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}

function catalogTab(): string {
  return `<div class="section">
    <h2>三个服务,一个薄 IPC 层</h2>
    <p class="hint">IPC 只做参数校验与转发;文件、URL、对话框逻辑都在 <code>main/services/</code>,可以用 Vitest 直接测。</p>
    <div class="service-grid">
      ${services
        .map(
          (
            service,
          ) => `<div class="card service-card" data-testid="service-card">
            <div class="card-label">${service.name}</div>
            <div class="mono">${service.deps}</div>
            <ul class="method-list">
              ${service.methods.map((method) => `<li><code>${method}</code></li>`).join("")}
            </ul>
            <p class="hint">${service.note}</p>
          </div>`,
        )
        .join("")}
    </div>
    <div class="panel">
      <div class="panel-label">为什么不是把 fs 写在 ipcMain.handle 里</div>
      <p class="hint">service 不依赖窗口,测试可以直接 new 一个临时目录;IPC 只有 30 行,改通道不会碰业务逻辑;同一服务可以被菜单、托盘、CLI 复用。</p>
    </div>
  </div>`;
}

function notesTab(): string {
  return `<div class="section">
    <h2>笔记服务</h2>
    <div class="row">
      <input id="note-id" data-testid="note-id" value="${escapeHtml(state.noteId)}" />
      <button class="tab active" id="save-button" data-testid="save-button">保存</button>
      <button class="mini" id="read-button" data-testid="read-button">读取</button>
      <button class="mini" id="delete-button" data-testid="delete-button">删除</button>
    </div>
    <textarea id="note-content" data-testid="note-content" rows="4">${escapeHtml(state.content)}</textarea>
    <table class="table" data-testid="note-table">
      <thead><tr><th>id</th><th>大小</th><th>更新时间</th></tr></thead>
      <tbody>
        ${state.notes
          .map(
            (note) => `<tr data-testid="note-row" data-id="${note.id}">
              <td><code>${escapeHtml(note.id)}</code></td>
              <td>${note.sizeBytes} B</td>
              <td><code>${time(note.updatedAt)}</code></td>
            </tr>`,
          )
          .join("")}
      </tbody>
    </table>
    <div class="panel">
      <div class="panel-label">最后一次响应</div>
      <pre class="code" data-testid="response-json">${state.response ? json(state.response) : "(还没有调用)"}</pre>
    </div>
  </div>`;
}

function shellTab(): string {
  const allowed = state.shellResult?.allowed;
  const blocked = state.shellResult?.blocked;
  const allowedText = allowed
    ? allowed.ok
      ? `OK · ${allowed.value.url}${allowed.value.dryRun ? "(dryRun)" : ""}`
      : allowed.error.code
    : "—";
  const blockedText = blocked
    ? blocked.ok
      ? "OK(不应出现)"
      : blocked.error.code
    : "—";
  return `<div class="section">
    <h2>Shell 白名单</h2>
    <p class="hint">允许:<code>example.com</code>、<code>www.electronjs.org</code>;只允许 <code>https</code>。</p>
    <div class="row">
      <input id="shell-url" data-testid="shell-url" value="${escapeHtml(state.shellUrl)}" />
      <button class="tab active" id="open-button" data-testid="open-button">打开链接</button>
    </div>
    <table class="table" data-testid="shell-table">
      <tbody>
        <tr><td>白名单链接</td><td><code data-testid="allowed-text">${escapeHtml(allowedText)}</code></td></tr>
        <tr><td>非白名单链接</td><td><code data-testid="blocked-text">${escapeHtml(blockedText)}</code></td></tr>
      </tbody>
    </table>
    <div class="panel">
      <div class="panel-label">被拒绝时的结构化错误</div>
      <pre class="code" data-testid="shell-json">${blocked && !blocked.ok ? json(blocked.error) : "(还没有调用)"}</pre>
    </div>
    <h2>文件对话框</h2>
    <div class="row">
      <button class="mini" id="pick-button" data-testid="pick-button">选择笔记文件</button>
      <span class="badge" data-testid="picked-name">${escapeHtml(state.picked?.name ?? "未选择")}</span>
    </div>
    <p class="hint">smoke 模式用固定的 <code>welcome.md</code> 替代真实对话框;生产才调用系统选择器。</p>
  </div>`;
}

function render(): void {
  const root = document.querySelector<HTMLDivElement>("#app");
  if (!root) return;
  const body =
    state.tab === "catalog"
      ? catalogTab()
      : state.tab === "notes"
        ? notesTab()
        : shellTab();
  root.innerHTML = `
    <header class="header">
      <div>
        <h1 data-testid="app-title">服务层工作台</h1>
        <p class="subtitle">notes · shell · dialog · 薄 IPC 层</p>
      </div>
      <nav class="tabs">
        ${tabs
          .map(
            (tab) =>
              `<button class="tab${state.tab === tab.id ? " active" : ""}" data-tab="${tab.id}" data-testid="tab-${tab.id}">${tab.label}</button>`,
          )
          .join("")}
      </nav>
    </header>
    <main class="content">${body}</main>`;

  for (const button of root.querySelectorAll<HTMLButtonElement>("[data-tab]")) {
    button.addEventListener("click", () => {
      const tab = button.dataset.tab;
      if (tab === "catalog" || tab === "notes" || tab === "shell") {
        state.tab = tab;
        render();
      }
    });
  }
  const idInput = (): string =>
    root.querySelector<HTMLInputElement>("#note-id")?.value ?? state.noteId;
  const contentInput = (): string =>
    root.querySelector<HTMLTextAreaElement>("#note-content")?.value ??
    state.content;
  root.querySelector("#save-button")?.addEventListener("click", () => {
    state.noteId = idInput();
    state.content = contentInput();
    void save();
  });
  root.querySelector("#read-button")?.addEventListener("click", () => {
    state.noteId = idInput();
    void read();
  });
  root.querySelector("#delete-button")?.addEventListener("click", () => {
    state.noteId = idInput();
    void remove();
  });
  for (const row of root.querySelectorAll<HTMLTableRowElement>("[data-id]")) {
    row.addEventListener("click", () => {
      state.noteId = row.dataset.id ?? "";
      void read();
    });
  }
  root.querySelector("#open-button")?.addEventListener("click", () => {
    state.shellUrl =
      root.querySelector<HTMLInputElement>("#shell-url")?.value ?? "";
    void openUrl();
  });
  root.querySelector("#pick-button")?.addEventListener("click", () => {
    void pick();
  });
}

async function reload(): Promise<void> {
  const response = await window.api.listNotes();
  if (response.ok) state.notes = response.value;
}

async function save(): Promise<void> {
  if (state.busy) return;
  state.busy = true;
  try {
    state.response = await window.api.writeNote(state.noteId, state.content);
    await reload();
  } finally {
    state.busy = false;
    render();
  }
}

async function read(): Promise<void> {
  if (state.busy) return;
  state.busy = true;
  try {
    const response = await window.api.readNote(state.noteId);
    state.response = response;
    if (response.ok) {
      state.content = response.value.content;
      state.tab = "notes";
    }
  } finally {
    state.busy = false;
    render();
  }
}

async function remove(): Promise<void> {
  if (state.busy) return;
  state.busy = true;
  try {
    state.response = await window.api.removeNote(state.noteId);
    await reload();
  } finally {
    state.busy = false;
    render();
  }
}

async function openUrl(): Promise<void> {
  const result = await window.api.openUrl(state.shellUrl);
  if (result.ok) {
    state.shellResult = { ...(state.shellResult ?? {}), allowed: result };
  } else {
    state.shellResult = { ...(state.shellResult ?? {}), blocked: result };
  }
  render();
}

async function pick(): Promise<void> {
  const response = await window.api.pickFile();
  state.picked = response.ok ? response.value : null;
  render();
}

function boot(): void {
  render();
  window.__setTab = (tab) => {
    state.tab = tab;
    render();
  };
  window.__snapshot = () => ({
    tab: state.tab,
    notes: state.notes.length,
    picked: state.picked?.name ?? null,
  });
  window.__smoke = async () => {
    await window.api.resetNotes();
    await window.api.writeNote(
      "welcome",
      "# 你好\n服务层把 fs 放在 main/services,IPC 只做校验。",
    );
    await window.api.writeNote("second-note", "第二条笔记");
    const list = await window.api.listNotes();
    const read = await window.api.readNote("welcome");
    const bad = await window.api.readNote("../escape");
    const allowed = await window.api.openUrl("https://example.com/docs");
    const blocked = await window.api.openUrl("http://example.com");
    const picked = await window.api.pickFile();

    state.notes = list.ok ? list.value : [];
    state.response = read;
    state.content = read.ok ? read.value.content : "";
    state.shellResult = { allowed, blocked };
    state.picked = picked.ok ? picked.value : null;
    state.tab = "catalog";
    render();

    return {
      notes: state.notes.length,
      readBytes: read.ok ? read.value.content.length : 0,
      badId: bad.ok ? "OK" : bad.error.code,
      allowed: allowed.ok,
      blocked: blocked.ok ? "OK" : blocked.error.code,
      picked: state.picked?.name ?? "none",
    };
  };
}

boot();