electron-util
Version:
Useful utilities for Electron apps and modules
45 lines (43 loc) • 1.54 kB
JavaScript
import { screen, } from 'electron';
import { is } from '../shared/index.js';
import { activeWindow } from './active-window.js';
/**
@returns The height of the menu bar on macOS, or `0` if not macOS.
*/
export const menuBarHeight = () => is.macos ? screen.getPrimaryDisplay().workArea.y : 0;
/**
Get the [bounds](https://electronjs.org/docs/api/browser-window#wingetbounds) of a window as if it was centered on the screen.
@returns Bounds of a window.
*/
export const getWindowBoundsCentered = (options) => {
const window = options?.window ?? activeWindow();
if (!window) {
throw new Error('No active window');
}
const [width, height] = window.getSize();
const windowSize = options?.size ?? { width: width ?? 0, height: height ?? 0 };
const screenSize = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea;
const x = Math.floor(screenSize.x + (screenSize.width / 2) - (windowSize.width / 2));
const y = Math.floor(((screenSize.height + screenSize.y) / 2) - (windowSize.height / 2));
return {
x,
y,
...windowSize,
};
};
/**
Center a window on the screen.
*/
export const centerWindow = (options) => {
const window = options?.window ?? activeWindow();
if (!window) {
throw new Error('No active window');
}
const resolvedOptions = {
window,
animated: false,
...options,
};
const bounds = getWindowBoundsCentered(resolvedOptions);
window.setBounds(bounds, resolvedOptions.animated ?? false);
};