From 15ac2b5815e3599f09d8347514de51d178655be0 Mon Sep 17 00:00:00 2001 From: qier222 Date: Tue, 5 Jan 2021 22:20:16 +0800 Subject: [PATCH] feat(electron): add tray for Windows --- src/background.js | 13 +++++++++++++ src/electron/tray.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/electron/tray.js diff --git a/src/background.js b/src/background.js index 664010f..8d2b105 100644 --- a/src/background.js +++ b/src/background.js @@ -5,6 +5,7 @@ import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer"; import { startNeteaseMusicApi } from "./electron/services"; import { initIpcMain } from "./electron/ipcMain.js"; import { createMenu } from "./electron/menu"; +import { createTray } from "@/electron/tray"; import { createTouchBar } from "./electron/touchBar"; import { createDockMenu } from "./electron/dockMenu"; import { autoUpdater } from "electron-updater"; @@ -15,6 +16,7 @@ import Store from "electron-store"; class Background { constructor() { this.window = null; + this.tray = null; this.store = new Store({ windowWidth: { width: { type: "number", default: 1440 }, @@ -101,6 +103,11 @@ class Background { // hide menu bar on Microsoft Windows and Linux this.window.setMenuBarVisibility(false); + // create tray only for Microsoft windows + if (process.platform === "win32") { + this.tray = createTray(this.window); + } + if (process.env.WEBPACK_DEV_SERVER_URL) { // Load the url of the dev server if in development mode this.window.loadURL(process.env.WEBPACK_DEV_SERVER_URL); @@ -164,6 +171,12 @@ class Background { this.store.set("window", { height, width }); }); + this.window.on("minimize", () => { + if (process.platform === "win32") { + this.window.hide(); + } + }); + this.window.webContents.on("new-window", function (e, url) { e.preventDefault(); shell.openExternal(url); diff --git a/src/electron/tray.js b/src/electron/tray.js new file mode 100644 index 0000000..833d8bd --- /dev/null +++ b/src/electron/tray.js @@ -0,0 +1,37 @@ +/* global __static */ +import path from "path"; +import { app, nativeImage, Tray, Menu } from "electron"; + +export function createTray(win) { + let icon = nativeImage + .createFromPath(path.join(__static, "img/icons/menu@88.png")) + .resize({ + height: 20, + width: 20, + }); + let tray = new Tray(icon); + + tray.setToolTip("YesPlayMusic"); + + tray.on("click", () => { + if (win && win.isVisible()) { + win.hide(); + } else { + win.show(); + } + }); + + tray.on("right-click", () => { + const contextMenu = Menu.buildFromTemplate([ + { + label: "Quit", + click: () => { + app.exit(); + }, + }, + ]); + tray.popUpContextMenu(contextMenu); + }); + + return tray; +}