import type { AuxRole, Rect, WindowInfo, WindowsSnapshot } from "../shared/ipc";
function escape(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
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 = `
`;
const windowsEl = root.querySelector('[data-testid="windows"]');
const openCount = root.querySelector(
'[data-testid="open-count"]',
);
const platform = root.querySelector('[data-testid="platform"]');
const storePath = root.querySelector(
'[data-testid="store-path"]',
);
const storeJson = root.querySelector(
'[data-testid="store-json"]',
);
const displays = root.querySelector('[data-testid="displays"]');
const eventLog = root.querySelector('[data-testid="event-log"]');
const lastMessage = root.querySelector(
'[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) => `
${display.id}
${formatBounds(display.workArea)}
@${display.scaleFactor}x${display.primary ? " · 主" : ""}
`,
)
.join("");
}
if (eventLog) {
eventLog.innerHTML =
state.events.length === 0
? `暂无事件`
: state.events
.map(
(event) => `
${time(event.at)}
${event.source}
${escape(event.text)}
`,
)
.join("");
}
}
function windowCard(info: WindowInfo, snapshot: WindowsSnapshot): string {
const display = snapshot.displays.find(
(item) => item.id === info.displayId,
);
return `
- bounds
- ${formatBounds(info.bounds)}
- display
- ${display ? `${display.id} · ${display.workArea.width}×${display.workArea.height}` : "?"}
${
info.role === "main"
? `主窗口不关闭`
: ``
}
`;
}
window.api.windows.onChange((next) => {
state = next;
render();
});
void window.api.windows.get().then((next) => {
state = next;
render();
});
for (const button of root.querySelectorAll(
"[data-create]",
)) {
button.addEventListener("click", () => {
const next = button.dataset.create as AuxRole | undefined;
if (next) void window.api.windows.create(next);
});
}
root
.querySelector('[data-testid="restore"]')
?.addEventListener("click", () => {
void window.api.windows.restore();
});
root
.querySelector('[data-testid="reset"]')
?.addEventListener("click", () => {
void window.api.windows.reset();
});
windowsEl?.addEventListener("click", (event) => {
const target = event.target as HTMLElement;
const button = target.closest("[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 = `
辅助窗口
${roleLabel(auxRole)}
#${selfId}
与主窗口通信
消息经主进程转发,辅助窗口之间不直接互连。
`;
const boundsEl = root.querySelector(
'[data-testid="aux-bounds"]',
);
const displayEl = root.querySelector(
'[data-testid="aux-display"]',
);
const sentEl = root.querySelector('[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('[data-testid="aux-message"]')
?.addEventListener("click", () => {
void window.api.windows
.message(`来自${roleLabel(auxRole)}的消息`)
.then(() => {
if (sentEl) sentEl.textContent = "已发送";
});
});
root
.querySelector('[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('[data-testid="aux-close"]')
?.addEventListener("click", () => {
void window.api.windows.close(selfId);
});
}