示例工程 30-multi-window-state

30-multi-window-state/app/src/App.ts

typescript · 13 KB

import type { AuxRole, Rect, WindowInfo, WindowsSnapshot } from "../shared/ipc";

function escape(text: string): string {
  return text.replace(/[&<>"]/g, (char) => {
    if (char === "&") return "&amp;";
    if (char === "<") return "&lt;";
    if (char === ">") return "&gt;";
    return "&quot;";
  });
}

function formatBounds(bounds: Rect): string {
  return `${bounds.x},${bounds.y} · ${bounds.width}×${bounds.height}`;
}

function roleLabel(role: string): string {
  if (role === "main") return "主窗口";
  if (role === "settings") return "设置";
  if (role === "inspector") return "检查器";
  return "便签";
}

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

const params = new URLSearchParams(window.location.search);
const role = params.get("role") ?? "main";
const selfId = Number(params.get("id") ?? "0");

export function mountApp(root: HTMLElement): void {
  if (role === "main") {
    mountHub(root);
  } else {
    mountAux(root, role as AuxRole);
  }
}

function mountHub(root: HTMLElement): void {
  root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <h1>多窗口状态工作台</h1>
          <span class="pill" data-testid="open-count">—</span>
          <span class="pill" data-testid="platform">—</span>
        </div>
        <div class="actions">
          <button class="btn" data-create="settings" data-testid="create-settings">新建设置</button>
          <button class="btn" data-create="inspector" data-testid="create-inspector">新建检查器</button>
          <button class="btn" data-create="note" data-testid="create-note">新建便签</button>
          <button class="btn" data-testid="restore">恢复上次会话</button>
          <button class="btn" data-testid="reset">重置布局</button>
        </div>
      </header>

      <main class="layout">
        <section class="windows" data-testid="windows"></section>
        <aside class="side">
          <div class="card pad">
            <div class="muted small">最后消息</div>
            <div class="message" data-testid="last-message">—</div>
          </div>
          <div class="card pad">
            <div class="card-head">
              <h2>持久化</h2>
              <code class="muted small" data-testid="store-path">—</code>
            </div>
            <pre class="json" data-testid="store-json"></pre>
          </div>
          <div class="card pad">
            <h2>显示器</h2>
            <ul class="displays" data-testid="displays"></ul>
          </div>
          <div class="card pad">
            <h2>事件</h2>
            <ul class="events" data-testid="event-log"></ul>
          </div>
        </aside>
      </main>
    </div>
  `;

  const windowsEl = root.querySelector<HTMLElement>('[data-testid="windows"]');
  const openCount = root.querySelector<HTMLElement>(
    '[data-testid="open-count"]',
  );
  const platform = root.querySelector<HTMLElement>('[data-testid="platform"]');
  const storePath = root.querySelector<HTMLElement>(
    '[data-testid="store-path"]',
  );
  const storeJson = root.querySelector<HTMLElement>(
    '[data-testid="store-json"]',
  );
  const displays = root.querySelector<HTMLElement>('[data-testid="displays"]');
  const eventLog = root.querySelector<HTMLElement>('[data-testid="event-log"]');
  const lastMessage = root.querySelector<HTMLElement>(
    '[data-testid="last-message"]',
  );

  let state: WindowsSnapshot | null = null;

  function render(): void {
    if (!state) return;
    if (openCount) openCount.textContent = `${state.windows.length} 个窗口`;
    if (platform) platform.textContent = `恢复 ${state.restoredCount}`;
    if (storePath) storePath.textContent = state.storePath;
    if (storeJson)
      storeJson.textContent = JSON.stringify(state.persisted, null, 2);
    if (lastMessage) lastMessage.textContent = state.lastMessage || "—";
    if (windowsEl) {
      windowsEl.innerHTML = state.windows
        .map((info) => windowCard(info, state as WindowsSnapshot))
        .join("");
    }
    if (displays) {
      displays.innerHTML = state.displays
        .map(
          (display) => `
          <li>
            <code>${display.id}</code>
            <span>${formatBounds(display.workArea)}</span>
            <span class="muted">@${display.scaleFactor}x${display.primary ? " · 主" : ""}</span>
          </li>`,
        )
        .join("");
    }
    if (eventLog) {
      eventLog.innerHTML =
        state.events.length === 0
          ? `<li class="muted">暂无事件</li>`
          : state.events
              .map(
                (event) => `
              <li>
                <span class="muted">${time(event.at)}</span>
                <code>${event.source}</code>
                <span>${escape(event.text)}</span>
              </li>`,
              )
              .join("");
    }
  }

  function windowCard(info: WindowInfo, snapshot: WindowsSnapshot): string {
    const display = snapshot.displays.find(
      (item) => item.id === info.displayId,
    );
    return `
      <article class="card window" data-testid="window-card" data-role="${info.role}" data-id="${info.id}">
        <header>
          <div>
            <h2>${roleLabel(info.role)}</h2>
            <code class="muted small">#${info.id}</code>
          </div>
          <span class="pill ${info.focused ? "ok" : ""}">
            ${info.focused ? "焦点" : info.visible ? "可见" : "隐藏"}
          </span>
        </header>
        <dl>
          <div><dt>bounds</dt><dd data-testid="window-bounds">${formatBounds(info.bounds)}</dd></div>
          <div><dt>display</dt><dd>${display ? `${display.id} · ${display.workArea.width}×${display.workArea.height}` : "?"}</dd></div>
        </dl>
        <div class="row">
          <button class="btn" data-action="focus" data-id="${info.id}">聚焦</button>
          <button class="btn" data-action="move" data-id="${info.id}">移动 +20</button>
          ${
            info.role === "main"
              ? `<span class="muted small">主窗口不关闭</span>`
              : `<button class="btn danger" data-action="close" data-id="${info.id}">关闭</button>`
          }
        </div>
      </article>`;
  }

  window.api.windows.onChange((next) => {
    state = next;
    render();
  });
  void window.api.windows.get().then((next) => {
    state = next;
    render();
  });

  for (const button of root.querySelectorAll<HTMLButtonElement>(
    "[data-create]",
  )) {
    button.addEventListener("click", () => {
      const next = button.dataset.create as AuxRole | undefined;
      if (next) void window.api.windows.create(next);
    });
  }
  root
    .querySelector<HTMLButtonElement>('[data-testid="restore"]')
    ?.addEventListener("click", () => {
      void window.api.windows.restore();
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="reset"]')
    ?.addEventListener("click", () => {
      void window.api.windows.reset();
    });

  windowsEl?.addEventListener("click", (event) => {
    const target = event.target as HTMLElement;
    const button = target.closest<HTMLButtonElement>("[data-action]");
    if (!button) return;
    const id = Number(button.dataset.id);
    if (!Number.isFinite(id)) return;
    const action = button.dataset.action;
    if (action === "focus") void window.api.windows.focus(id);
    if (action === "close") void window.api.windows.close(id);
    if (action === "move") void window.api.windows.move(id, 20, 12);
  });

  window.__prepareShots = async (stage) => {
    await window.api.windows.reset();
    await new Promise((resolve) => setTimeout(resolve, 80));
    await window.api.windows.create("settings");
    await window.api.windows.create("inspector");
    await window.api.windows.create("note");
    if (stage === "restore") {
      await new Promise((resolve) => setTimeout(resolve, 500));
      await window.api.windows.restore();
    }
    await new Promise((resolve) => setTimeout(resolve, 200));
  };
  window.__smoke = async () => {
    const wait = (ms: number) =>
      new Promise((resolve) => setTimeout(resolve, ms));
    const api = window.api.windows;
    await api.reset();
    await wait(100);
    await api.create("settings");
    await api.create("settings");
    await api.create("note");
    await api.create("inspector");
    await wait(200);
    const created = await api.get();
    const singletonCount = created.windows.filter(
      (item) => item.role === "settings",
    ).length;

    const note = created.windows.find((item) => item.role === "note");
    const before = note?.bounds;
    let moved = false;
    if (note && before) {
      await api.move(note.id, 24, 16);
      await wait(150);
      const afterState = await api.get();
      const after = afterState.windows.find((item) => item.role === "note");
      moved =
        after !== undefined &&
        (after.bounds.x !== before.x || after.bounds.y !== before.y);
    }

    await api.message("来自便签的测试消息");
    await wait(100);
    const messaged = await api.get();
    const messageSeen = messaged.lastMessage.includes("测试消息");
    await wait(400);
    const beforeRestore = await api.get();
    const oldIds = beforeRestore.windows
      .filter((item) => item.role !== "main")
      .map((item) => item.id);
    await api.restore();
    await wait(500);
    const restored = await api.get();
    const auxWindows = restored.windows.filter((item) => item.role !== "main");
    const restoredIdsChanged =
      auxWindows.length === 3 &&
      auxWindows.every((item) => !oldIds.includes(item.id));
    const clamped = restored.windows.every((item) => {
      const display = restored.displays.find(
        (entry) => entry.id === item.displayId,
      );
      if (!display) return false;
      const area = display.workArea;
      return (
        item.bounds.x >= area.x &&
        item.bounds.y >= area.y &&
        item.bounds.x + item.bounds.width <= area.x + area.width &&
        item.bounds.y + item.bounds.height <= area.y + area.height
      );
    });

    return {
      roles: restored.windows.map((item) => item.role),
      singletonCount,
      moved,
      messageSeen,
      persistedOpen: beforeRestore.persisted.open.length,
      restoredRoles: auxWindows.map((item) => item.role),
      restoredIdsChanged,
      clamped,
      lastEvent: restored.events[0]?.text ?? "",
    };
  };
}

function mountAux(root: HTMLElement, auxRole: AuxRole): void {
  root.innerHTML = `
    <div class="aux">
      <header class="aux-head">
        <div>
          <div class="muted small">辅助窗口</div>
          <h1 data-testid="aux-role">${roleLabel(auxRole)}</h1>
        </div>
        <code class="muted" data-testid="aux-id">#${selfId}</code>
      </header>
      <div class="card pad">
        <div class="muted small">窗口范围</div>
        <div class="aux-bounds" data-testid="aux-bounds">—</div>
        <div class="muted small" data-testid="aux-display">—</div>
      </div>
      <div class="card pad">
        <div class="muted small">与主窗口通信</div>
        <p class="small muted">
          消息经主进程转发,辅助窗口之间不直接互连。
        </p>
        <button class="btn primary" data-testid="aux-message">向主窗口发消息</button>
        <button class="btn" data-testid="aux-focus-main">聚焦主窗口</button>
        <div class="muted small" data-testid="aux-sent"></div>
      </div>
      <div class="card pad">
        <button class="btn danger" data-testid="aux-close">关闭这个窗口</button>
      </div>
    </div>
  `;

  const boundsEl = root.querySelector<HTMLElement>(
    '[data-testid="aux-bounds"]',
  );
  const displayEl = root.querySelector<HTMLElement>(
    '[data-testid="aux-display"]',
  );
  const sentEl = root.querySelector<HTMLElement>('[data-testid="aux-sent"]');

  let state: WindowsSnapshot | null = null;
  function render(): void {
    if (!state) return;
    const self = state.windows.find((item) => item.id === selfId);
    if (boundsEl) boundsEl.textContent = self ? formatBounds(self.bounds) : "?";
    if (displayEl) {
      const display = state.displays.find(
        (item) => item.id === self?.displayId,
      );
      displayEl.textContent = display
        ? `显示器 ${display.id} · ${display.workArea.width}×${display.workArea.height} @${display.scaleFactor}x`
        : "";
    }
  }

  window.api.windows.onChange((next) => {
    state = next;
    render();
  });
  void window.api.windows.get().then((next) => {
    state = next;
    render();
  });

  root
    .querySelector<HTMLButtonElement>('[data-testid="aux-message"]')
    ?.addEventListener("click", () => {
      void window.api.windows
        .message(`来自${roleLabel(auxRole)}的消息`)
        .then(() => {
          if (sentEl) sentEl.textContent = "已发送";
        });
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="aux-focus-main"]')
    ?.addEventListener("click", () => {
      const main = state?.windows.find((item) => item.role === "main");
      if (main) void window.api.windows.focus(main.id);
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="aux-close"]')
    ?.addEventListener("click", () => {
      void window.api.windows.close(selfId);
    });
}