Files
Toju/electron/window/create-window.ts

92 lines
2.4 KiB
TypeScript

import { app, BrowserWindow, shell } from 'electron';
import * as fs from 'fs';
import * as path from 'path';
let mainWindow: BrowserWindow | null = null;
function getAssetPath(...segments: string[]): string {
const basePath = app.isPackaged
? path.join(process.resourcesPath, 'images')
: path.join(__dirname, '..', '..', '..', 'images');
return path.join(basePath, ...segments);
}
function getExistingAssetPath(...segments: string[]): string | undefined {
const assetPath = getAssetPath(...segments);
return fs.existsSync(assetPath) ? assetPath : undefined;
}
function getWindowIconPath(): string | undefined {
if (process.platform === 'win32')
return getExistingAssetPath('windows', 'icon.ico');
if (process.platform === 'linux')
return getExistingAssetPath('icon.png');
return undefined;
}
export function getDockIconPath(): string | undefined {
return getExistingAssetPath('macos', '1024x1024.png');
}
export function getMainWindow(): BrowserWindow | null {
return mainWindow;
}
export async function createWindow(): Promise<void> {
const windowIconPath = getWindowIconPath();
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
frame: false,
titleBarStyle: 'hidden',
backgroundColor: '#0a0a0f',
...(windowIconPath ? { icon: windowIconPath } : {}),
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, '..', 'preload.js'),
webSecurity: true
}
});
if (process.env['NODE_ENV'] === 'development') {
const devUrl = process.env['SSL'] === 'true'
? 'https://localhost:4200'
: 'http://localhost:4200';
await mainWindow.loadURL(devUrl);
if (process.env['DEBUG_DEVTOOLS'] === '1') {
mainWindow.webContents.openDevTools();
}
} else {
await mainWindow.loadFile(path.join(__dirname, '..', '..', 'client', 'browser', 'index.html'));
}
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
mainWindow.webContents.on('will-navigate', (event, url) => {
const currentUrl = mainWindow?.webContents.getURL();
const isSameOrigin = new URL(url).origin === new URL(currentUrl || '').origin;
if (!isSameOrigin) {
event.preventDefault();
shell.openExternal(url);
}
});
}