Nativefier/app/src/components/menu.ts

425 lines
11 KiB
TypeScript
Raw Normal View History

import * as fs from 'fs';
import path from 'path';
import {
BrowserWindow,
clipboard,
Menu,
MenuItem,
MenuItemConstructorOptions,
} from 'electron';
import { cleanupPlainText, isOSX, openExternal } from '../helpers/helpers';
import * as log from '../helpers/loggingHelper';
import {
clearAppData,
getCurrentURL,
goBack,
goForward,
goToURL,
zoomIn,
zoomOut,
zoomReset,
} from '../helpers/windowHelpers';
import { OutputOptions } from '../../../shared/src/options/model';
type BookmarksLink = {
type: 'link';
title: string;
url: string;
shortcut?: string;
};
type BookmarksSeparator = {
type: 'separator';
};
type BookmarkConfig = BookmarksLink | BookmarksSeparator;
type BookmarksMenuConfig = {
menuLabel: string;
bookmarks: BookmarkConfig[];
};
export function createMenu(
options: OutputOptions,
mainWindow: BrowserWindow,
): void {
log.debug('createMenu', { options, mainWindow });
const menuTemplate = generateMenu(options, mainWindow);
injectBookmarks(menuTemplate);
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
export function generateMenu(
options: {
disableDevTools: boolean;
nativefierVersion: string;
zoom?: number;
},
mainWindow: BrowserWindow,
): MenuItemConstructorOptions[] {
const { nativefierVersion, zoom, disableDevTools } = options;
2018-05-24 09:02:44 +02:00
const zoomResetLabel =
!zoom || zoom === 1.0
2018-05-24 09:02:44 +02:00
? 'Reset Zoom'
: `Reset Zoom (to ${(zoom * 100).toFixed(1)}%, set at build time)`;
const editMenu: MenuItemConstructorOptions = {
label: '&Edit',
submenu: [
{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
role: 'undo',
},
{
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
role: 'redo',
},
{
type: 'separator',
},
{
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
role: 'cut',
},
{
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
role: 'copy',
},
{
label: 'Copy as Plain Text',
accelerator: 'CmdOrCtrl+Shift+C',
click: (): void => {
// We use clipboard.readText to strip down formatting
const text = clipboard.readText('selection');
clipboard.writeText(cleanupPlainText(text), 'clipboard');
},
},
{
label: 'Copy Current URL',
accelerator: 'CmdOrCtrl+L',
click: (): void => clipboard.writeText(getCurrentURL()),
},
{
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
role: 'paste',
},
{
label: 'Paste and Match Style',
// https://github.com/nativefier/nativefier/issues/404
// Apple's HIG lists this shortcut for paste and match style
// https://support.apple.com/en-us/HT209651
accelerator: isOSX() ? 'Option+Shift+Cmd+V' : 'Ctrl+Shift+V',
role: 'pasteAndMatchStyle',
},
{
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
role: 'selectAll',
},
{
label: 'Clear App Data',
click: (
item: MenuItem,
focusedWindow: BrowserWindow | undefined,
): void => {
log.debug('Clear App Data.click', {
item,
focusedWindow,
mainWindow,
});
if (!focusedWindow) {
focusedWindow = mainWindow;
}
clearAppData(focusedWindow).catch((err) =>
log.error('clearAppData ERROR', err),
);
},
},
],
};
const viewMenu: MenuItemConstructorOptions = {
label: '&View',
submenu: [
{
label: 'Back',
accelerator: isOSX() ? 'CmdOrAlt+Left' : 'Alt+Left',
click: goBack,
},
{
label: 'BackAdditionalShortcut',
visible: false,
acceleratorWorksWhenHidden: true,
accelerator: 'CmdOrCtrl+[', // What old versions of Nativefier used, kept for backwards compat
click: goBack,
},
{
label: 'Forward',
accelerator: isOSX() ? 'Cmd+Right' : 'Alt+Right',
click: goForward,
},
{
label: 'ForwardAdditionalShortcut',
visible: false,
acceleratorWorksWhenHidden: true,
accelerator: 'CmdOrCtrl+]', // What old versions of Nativefier used, kept for backwards compat
click: goForward,
},
{
label: 'Reload',
role: 'reload',
},
{
type: 'separator',
},
{
label: 'Toggle Full Screen',
accelerator: isOSX() ? 'Ctrl+Cmd+F' : 'F11',
enabled: mainWindow.isFullScreenable() || isOSX(),
visible: mainWindow.isFullScreenable() || isOSX(),
click: (
item: MenuItem,
focusedWindow: BrowserWindow | undefined,
): void => {
log.debug('Toggle Full Screen.click()', {
item,
focusedWindow,
isFullScreen: focusedWindow?.isFullScreen(),
isFullScreenable: focusedWindow?.isFullScreenable(),
});
if (!focusedWindow) {
focusedWindow = mainWindow;
}
if (focusedWindow.isFullScreenable()) {
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
} else if (isOSX()) {
focusedWindow.setSimpleFullScreen(
!focusedWindow.isSimpleFullScreen(),
);
}
},
},
{
label: 'Zoom In',
accelerator: 'CmdOrCtrl+=',
click: zoomIn,
},
{
label: 'ZoomInAdditionalShortcut',
visible: false,
acceleratorWorksWhenHidden: true,
accelerator: 'CmdOrCtrl+numadd',
click: zoomIn,
},
{
label: 'Zoom Out',
accelerator: 'CmdOrCtrl+-',
click: zoomOut,
},
{
label: 'ZoomOutAdditionalShortcut',
visible: false,
acceleratorWorksWhenHidden: true,
accelerator: 'CmdOrCtrl+numsub',
click: zoomOut,
},
{
label: zoomResetLabel,
accelerator: 'CmdOrCtrl+0',
click: (): void => zoomReset(options),
},
{
label: 'ZoomResetAdditionalShortcut',
visible: false,
acceleratorWorksWhenHidden: true,
accelerator: 'CmdOrCtrl+num0',
click: (): void => zoomReset(options),
},
],
};
if (!disableDevTools) {
(viewMenu.submenu as MenuItemConstructorOptions[]).push(
{
type: 'separator',
},
{
label: 'Toggle Developer Tools',
accelerator: isOSX() ? 'Alt+Cmd+I' : 'Ctrl+Shift+I',
click: (item: MenuItem, focusedWindow: BrowserWindow | undefined) => {
log.debug('Toggle Developer Tools.click()', { item, focusedWindow });
if (!focusedWindow) {
focusedWindow = mainWindow;
}
focusedWindow.webContents.toggleDevTools();
},
},
);
}
const windowMenu: MenuItemConstructorOptions = {
label: '&Window',
role: 'window',
submenu: [
{
label: 'Minimize',
accelerator: 'CmdOrCtrl+M',
role: 'minimize',
},
{
label: 'Close',
accelerator: 'CmdOrCtrl+W',
role: 'close',
},
],
};
const helpMenu: MenuItemConstructorOptions = {
label: '&Help',
role: 'help',
submenu: [
{
label: `Built with Nativefier v${nativefierVersion}`,
click: (): void => {
openExternal('https://github.com/nativefier/nativefier').catch(
(err: unknown): void =>
log.error(
'Built with Nativefier v${nativefierVersion}.click ERROR',
err,
),
);
},
},
{
label: 'Report an Issue',
click: (): void => {
openExternal('https://github.com/nativefier/nativefier/issues').catch(
(err: unknown): void =>
log.error('Report an Issue.click ERROR', err),
);
},
},
],
};
let menuTemplate: MenuItemConstructorOptions[];
if (isOSX()) {
const electronMenu: MenuItemConstructorOptions = {
label: 'E&lectron',
submenu: [
{
label: 'Services',
role: 'services',
submenu: [],
},
{
type: 'separator',
},
{
label: 'Hide App',
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 21:50:01 +01:00
accelerator: 'Cmd+H',
role: 'hide',
},
{
label: 'Hide Others',
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 21:50:01 +01:00
accelerator: 'Cmd+Shift+H',
role: 'hideOthers',
},
{
label: 'Show All',
role: 'unhide',
},
{
type: 'separator',
},
{
label: 'Quit',
Revamp and move to TypeScript (#898) ## Breaking changes - Require **Node >= 8.10.0 and npm 5.6.0** - Move to **Electron 8.1.1**. - That's it. Lots of care went into breaking CLI & programmatic behavior as little as possible. **Please report regressions**. - Known issue: build may fail behind a proxy. Get in touch if you use one: https://github.com/jiahaog/nativefier/issues/907#issuecomment-596144768 ## Changes summary Nativefier didn't get much love recently, to the point that it's becoming hard to run on recent Node, due to old dependencies. Also, some past practices now seem weird, as better expressible by modern JS/TS, discouraging contributions including mine. Addressing this, and one thing leading to another, came a bigger-than-expected revamp, aiming at making Nativefier more **lean, stable, future-proof, user-friendly and dev-friendly**, while **not changing the CLI/programmatic interfaces**. Highlights: - **Require Node>=8**, as imposed by many of our dependencies. Node 8 is twice LTS, and easily available even in conservative Linux distros. No reason not to demand it. - **Default to Electron 8**. - **Bump** all dependencies to latest version, including electron-packager. - **Move to TS**. TS is great. As of today, I see no reason not to use it, and fight interface bugs at runtime rather than at compile time. With that, get rid of everything Babel/Webpack. - **Move away from Gulp**. Gulp's selling point is perf via streaming, but for small builds like Nativefier, npm tasks are plenty good and less dependency bloat. Gulp was the driver for this PR: broken on Node 12, and I didn't feel like just upgrading and keeping it. - Add tons of **verbose logs** everywhere it makes sense, to have a fine & clear trace of the program flow. This will be helpful to debug user-reported issues, and already helped me fix a few bugs. - With better simple logging, get rid of the quirky and buggy progress bar based on package `progress`. Nice logging (minimal by default, the verbose logging mentioned above is only used when passing `--verbose`) is better and one less dependency. - **Dump `async` package**, a relic from old callback-hell early Node. Also dump a few other micro-packages unnecessary now. - A first pass of code **cleanup** thanks to modern JS/TS features: fixes, simplifications, jsdoc type annotations to types, etc. - **Remove GitHub integrations Hound & CodeClimate**, which are more exotic than good'ol'linters, and whose signal-to-noise ratio is too low. - Quality: **Add tests** and add **Windows + macOS CI builds**. Also, add a **manual test script**, helping to quickly verify the hard-to-programatically-test stuff before releases, and limit regressions. - **Fix a very small number of existing bugs**. The goal of this PR was *not* to fix bugs, but to get Nativefier in better shape to do so. Bugfixes will come later. Still, these got addressed: - Add common `Alt`+`Left`/`Right` for previous/next navigation. - Improve #379: fix zoom with `Ctrl` + numpad `+`/`-` - Fix pinch-to-zoom (see https://github.com/jiahaog/nativefier/issues/379#issuecomment-598612128 )
2020-03-15 21:50:01 +01:00
accelerator: 'Cmd+Q',
role: 'quit',
},
],
};
(windowMenu.submenu as MenuItemConstructorOptions[]).push(
{
type: 'separator',
},
{
label: 'Bring All to Front',
role: 'front',
},
);
menuTemplate = [electronMenu, editMenu, viewMenu, windowMenu, helpMenu];
} else {
menuTemplate = [editMenu, viewMenu, windowMenu, helpMenu];
}
return menuTemplate;
}
function injectBookmarks(menuTemplate: MenuItemConstructorOptions[]): void {
const bookmarkConfigPath = path.join(__dirname, '..', 'bookmarks.json');
if (!fs.existsSync(bookmarkConfigPath)) {
return;
}
try {
const bookmarksMenuConfig = JSON.parse(
fs.readFileSync(bookmarkConfigPath, 'utf-8'),
) as BookmarksMenuConfig;
const submenu: MenuItemConstructorOptions[] =
bookmarksMenuConfig.bookmarks.map((bookmark) => {
switch (bookmark.type) {
case 'link':
if (!('title' in bookmark && 'url' in bookmark)) {
throw new Error(
'All links in the bookmarks menu must have a title and url.',
);
}
try {
new URL(bookmark.url);
} catch {
throw new Error('Bookmark URL "' + bookmark.url + '"is invalid.');
}
return {
label: bookmark.title,
click: (): void => {
goToURL(bookmark.url)?.catch((err: unknown): void =>
log.error(`${bookmark.title}.click ERROR`, err),
);
},
accelerator:
'shortcut' in bookmark ? bookmark.shortcut : undefined,
};
case 'separator':
return {
type: 'separator',
};
default:
throw new Error(
'A bookmarks menu entry has an invalid type; type must be one of "link", "separator".',
);
}
});
const bookmarksMenu: MenuItemConstructorOptions = {
label: bookmarksMenuConfig.menuLabel,
submenu,
};
// Insert custom bookmarks menu between menus "View" and "Window"
menuTemplate.splice(menuTemplate.length - 2, 0, bookmarksMenu);
} catch (err: unknown) {
log.error('Failed to load & parse bookmarks configuration JSON file.', err);
}
}