Files
makelore/electron/main/window-provider.ts
2026-09-29 19:50:25 +08:00

40 lines
1.3 KiB
TypeScript

import type { BrowserWindow } from 'electron';
export type MainWindowProvider = BrowserWindow | (() => BrowserWindow | null);
export type EnsureMainWindow = () => BrowserWindow | null;
export function resolveMainWindow(provider: MainWindowProvider): BrowserWindow | null {
const window = typeof provider === 'function' ? provider() : provider;
return window && !window.isDestroyed?.() ? window : null;
}
export function showMainWindow(window: BrowserWindow | null): void {
if (!window || window.isDestroyed()) return;
if (window.isMinimized()) window.restore();
window.show();
window.focus();
}
/** A newly reopened renderer must finish loading before it can receive menu actions. */
export function sendWhenWindowReady(
window: BrowserWindow | null,
channel: string,
...args: unknown[]
): void {
if (!window || window.isDestroyed() || window.webContents.isDestroyed()) return;
const contents = window.webContents;
const send = (): void => {
contents.removeListener('destroyed', cancel);
if (!window.isDestroyed() && !contents.isDestroyed()) contents.send(channel, ...args);
};
const cancel = (): void => {
contents.removeListener('did-finish-load', send);
};
if (contents.isLoadingMainFrame() || !contents.getURL()) {
contents.once('did-finish-load', send);
contents.once('destroyed', cancel);
} else {
send();
}
}