From 76a6e38376a01dbeee83161cdce9fe5e205b1523 Mon Sep 17 00:00:00 2001 From: Whitewater Date: Wed, 6 Nov 2024 02:29:16 -0800 Subject: [PATCH] feat: add application tray functionality (#1416) * feat: add app tray * chore: register app tray during bootstrap * feat: enhance app tray functionality * feat: add minimize to tray functionality in settings * chore: update i18n * fix: registering app tray when change lang * fix: hide tray setting in web * chore: update changelog * refactor: move minimize to tray setting to general * chore: clean code * chore: starting app in tray by default * refactor: remove unused effect in SettingDataControl * refactor: use template image --- apps/main/src/constants/app.ts | 3 + apps/main/src/helper.ts | 1 + apps/main/src/index.ts | 16 +++-- apps/main/src/lib/tray.ts | 67 ++++++++++++++++++ apps/main/src/tipc/app.ts | 2 + apps/main/src/tipc/setting.ts | 11 ++- apps/main/src/window.ts | 9 ++- apps/renderer/src/hooks/biz/useTraySetting.ts | 27 +++++++ .../modules/settings/tabs/data-control.tsx | 7 -- .../src/modules/settings/tabs/general.tsx | 21 +++++- changelog/next.md | 1 + locales/errors/en.json | 4 +- locales/native/en.json | 1 + locales/native/zh-CN.json | 1 + locales/settings/en.json | 2 + locales/settings/zh-CN.json | 2 + resources/tray-icon.png | Bin 0 -> 431 bytes 17 files changed, 152 insertions(+), 23 deletions(-) create mode 100644 apps/main/src/lib/tray.ts create mode 100644 apps/renderer/src/hooks/biz/useTraySetting.ts create mode 100644 resources/tray-icon.png diff --git a/apps/main/src/constants/app.ts b/apps/main/src/constants/app.ts index 1391eb05c..9f9441bdc 100644 --- a/apps/main/src/constants/app.ts +++ b/apps/main/src/constants/app.ts @@ -1,2 +1,5 @@ // 5min export const UNREAD_BACKGROUND_POLLING_INTERVAL = 1000 * 60 * 5 + +// https://github.com/electron/electron/issues/25081 +export const START_IN_TRAY_ARGS = "--start-in-tray" diff --git a/apps/main/src/helper.ts b/apps/main/src/helper.ts index 283e7d326..27cf9593b 100644 --- a/apps/main/src/helper.ts +++ b/apps/main/src/helper.ts @@ -7,3 +7,4 @@ const iconMap = { dev: path.join(__dirname, "../../static/icon-dev.png"), } export const getIconPath = () => iconMap[process.env.NODE_ENV === "development" ? "dev" : "prod"] +export const getTrayIconPath = () => path.join(__dirname, "../../resources/tray-icon.png") diff --git a/apps/main/src/index.ts b/apps/main/src/index.ts index 1bd54b868..5db8b71b8 100644 --- a/apps/main/src/index.ts +++ b/apps/main/src/index.ts @@ -11,9 +11,15 @@ import { initializeAppStage0, initializeAppStage1 } from "./init" import { updateProxy } from "./lib/proxy" import { handleUrlRouting } from "./lib/router" import { store } from "./lib/store" +import { registerAppTray } from "./lib/tray" import { setAuthSessionToken, updateNotificationsToken } from "./lib/user" import { registerUpdater } from "./updater" -import { createMainWindow, getMainWindow, windowStateStoreKey } from "./window" +import { + createMainWindow, + getMainWindow, + getMainWindowOrCreate, + windowStateStoreKey, +} from "./window" if (isDev) console.info("[main] env loaded:", env) @@ -65,6 +71,7 @@ function bootstrap() { updateProxy() registerUpdater() + registerAppTray() session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => { // remove Electron, Follow from user agent @@ -93,11 +100,8 @@ function bootstrap() { app.on("activate", () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. - if (BrowserWindow.getAllWindows().length === 0) { - mainWindow = createMainWindow() - } - - if (mainWindow) mainWindow.show() + mainWindow = getMainWindowOrCreate() + mainWindow.show() }) app.on("open-url", (_, url) => { diff --git a/apps/main/src/lib/tray.ts b/apps/main/src/lib/tray.ts new file mode 100644 index 000000000..7207ec3d0 --- /dev/null +++ b/apps/main/src/lib/tray.ts @@ -0,0 +1,67 @@ +import { name } from "@pkg" +import { app, Menu, nativeImage, Tray } from "electron" + +import { isMacOS } from "~/env" +import { getTrayIconPath } from "~/helper" + +import { getMainWindowOrCreate } from "../window" +import { t } from "./i18n" +import { store } from "./store" + +// https://www.electronjs.org/docs/latest/tutorial/tray + +let tray: Tray | null = null + +export const registerAppTray = () => { + if (!getTrayConfig()) return + if (tray) { + destroyAppTray() + } + + const icon = nativeImage.createFromPath(getTrayIconPath()) + // See https://stackoverflow.com/questions/41664208/electron-tray-icon-change-depending-on-dark-theme/41998326#41998326 + const trayIcon = icon.resize({ width: 16 }) + trayIcon.setTemplateImage(true) + tray = new Tray(trayIcon) + + const contextMenu = Menu.buildFromTemplate([ + { + label: t("menu.open", { name }), + click: showWindow, + }, + { label: t("menu.quit", { name }), click: () => app.quit() }, + ]) + tray.setContextMenu(contextMenu) + tray.setToolTip(app.getName()) + tray.on("click", showWindow) +} + +const showWindow = () => { + const mainWindow = getMainWindowOrCreate() + if (!mainWindow) return + if (mainWindow.isMinimized()) { + mainWindow.restore() + } else { + mainWindow.show() + } +} + +const destroyAppTray = () => { + if (tray) { + tray.destroy() + tray = null + } +} + +const DEFAULT_MINIMIZE_TO_TRAY = isMacOS ? false : true + +export const getTrayConfig = (): boolean => store.get("minimizeToTray") ?? DEFAULT_MINIMIZE_TO_TRAY + +export const setTrayConfig = (input: boolean) => { + store.set("minimizeToTray", input) + if (input) { + registerAppTray() + } else { + destroyAppTray() + } +} diff --git a/apps/main/src/tipc/app.ts b/apps/main/src/tipc/app.ts index 4416ca96d..3415a59ca 100644 --- a/apps/main/src/tipc/app.ts +++ b/apps/main/src/tipc/app.ts @@ -10,6 +10,7 @@ import { app, clipboard, dialog, screen } from "electron" import { registerMenuAndContextMenu } from "~/init" import { clearAllData, getCacheSize } from "~/lib/cleaner" import { store, StoreKey } from "~/lib/store" +import { registerAppTray } from "~/lib/tray" import { logger } from "~/logger" import { isWindows11 } from "../env" @@ -224,6 +225,7 @@ export const appRoute = { switchAppLocale: t.procedure.input().action(async ({ input }) => { i18n.changeLanguage(input) registerMenuAndContextMenu() + registerAppTray() app.commandLine.appendSwitch("lang", input) }), diff --git a/apps/main/src/tipc/setting.ts b/apps/main/src/tipc/setting.ts index 7bce61971..e6b4247b0 100644 --- a/apps/main/src/tipc/setting.ts +++ b/apps/main/src/tipc/setting.ts @@ -2,6 +2,9 @@ import { createRequire } from "node:module" import { app, nativeTheme } from "electron" +import { START_IN_TRAY_ARGS } from "~/constants/app" +import { getTrayConfig, setTrayConfig } from "~/lib/tray" + import { setDockCount } from "../lib/dock" import { setProxyConfig, updateProxy } from "../lib/proxy" import { store } from "../lib/store" @@ -10,12 +13,12 @@ import { t } from "./_instance" const require = createRequire(import.meta.url) export const settingRoute = { - getLoginItemSettings: t.procedure - .input() - .action(async () => await app.getLoginItemSettings()), + getLoginItemSettings: t.procedure.input().action(async () => app.getLoginItemSettings()), setLoginItemSettings: t.procedure.input().action(async ({ input }) => { app.setLoginItemSettings({ openAtLogin: input, + openAsHidden: true, + args: [START_IN_TRAY_ARGS], }) }), openSettingWindow: t.procedure.action(async () => createSettingWindow()), @@ -37,6 +40,8 @@ export const settingRoute = { store.set("appearance", input) }), + getMinimizeToTray: t.procedure.action(async () => getTrayConfig()), + setMinimizeToTray: t.procedure.input().action(async ({ input }) => setTrayConfig(input)), setDockBadge: t.procedure.input().action(async ({ input }) => { setDockCount(input) }), diff --git a/apps/main/src/window.ts b/apps/main/src/window.ts index ba11ee409..f62fd0201 100644 --- a/apps/main/src/window.ts +++ b/apps/main/src/window.ts @@ -4,8 +4,9 @@ import { fileURLToPath } from "node:url" import { is } from "@electron-toolkit/utils" import { callWindowExpose } from "@follow/shared/bridge" import type { BrowserWindowConstructorOptions } from "electron" -import { BrowserWindow, screen, shell } from "electron" +import { app, BrowserWindow, screen, shell } from "electron" +import { START_IN_TRAY_ARGS } from "./constants/app" import { isDev, isMacOS, isWindows, isWindows11 } from "./env" import { getIconPath } from "./helper" import { store } from "./lib/store" @@ -97,7 +98,9 @@ export function createWindow( }) window.on("ready-to-show", () => { - window?.show() + const shouldShowWindow = + !app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS) + if (shouldShowWindow) window.show() }) window.webContents.setWindowOpenHandler((details) => { @@ -282,7 +285,7 @@ export const getMainWindow = () => windows.mainWindow export const getMainWindowOrCreate = () => { if (!windows.mainWindow) { - createMainWindow() + return createMainWindow() } return windows.mainWindow } diff --git a/apps/renderer/src/hooks/biz/useTraySetting.ts b/apps/renderer/src/hooks/biz/useTraySetting.ts new file mode 100644 index 000000000..a27369d0f --- /dev/null +++ b/apps/renderer/src/hooks/biz/useTraySetting.ts @@ -0,0 +1,27 @@ +import { IN_ELECTRON } from "@follow/shared/constants" +import { atom, useAtomValue, useSetAtom } from "jotai" +import { useCallback } from "react" + +import { tipcClient } from "~/lib/client" + +const minimizeToTrayAtom = atom(false) + +minimizeToTrayAtom.onMount = (setAtom) => { + tipcClient?.getMinimizeToTray().then((proxy: boolean) => { + setAtom(proxy) + }) +} + +export const useMinimizeToTrayValue = () => useAtomValue(minimizeToTrayAtom) + +export const useSetMinimizeToTray = () => { + const setMinimizeToTray = useSetAtom(minimizeToTrayAtom) + return useCallback( + (value: boolean) => { + if (!IN_ELECTRON) return + setMinimizeToTray(value) + tipcClient?.setMinimizeToTray(value) + }, + [setMinimizeToTray], + ) +} diff --git a/apps/renderer/src/modules/settings/tabs/data-control.tsx b/apps/renderer/src/modules/settings/tabs/data-control.tsx index bdc550de9..ac1548e7c 100644 --- a/apps/renderer/src/modules/settings/tabs/data-control.tsx +++ b/apps/renderer/src/modules/settings/tabs/data-control.tsx @@ -4,7 +4,6 @@ import { Label } from "@follow/components/ui/label/index.jsx" import { Slider } from "@follow/components/ui/slider/index.js" import { env } from "@follow/shared/env" import { useQuery } from "@tanstack/react-query" -import { useEffect } from "react" import { useTranslation } from "react-i18next" import { setGeneralSetting, useGeneralSettingValue } from "~/atoms/settings/general" @@ -26,12 +25,6 @@ const { defineSettingItem, SettingBuilder } = createSetting( ) export const SettingDataControl = () => { const { t } = useTranslation("settings") - useEffect(() => { - tipcClient?.getLoginItemSettings().then((settings) => { - setGeneralSetting("appLaunchOnStartup", settings.openAtLogin) - }) - }, []) - const { present } = useModalStack() return ( diff --git a/apps/renderer/src/modules/settings/tabs/general.tsx b/apps/renderer/src/modules/settings/tabs/general.tsx index efe699259..7d73a9c15 100644 --- a/apps/renderer/src/modules/settings/tabs/general.tsx +++ b/apps/renderer/src/modules/settings/tabs/general.tsx @@ -23,10 +23,11 @@ import { useGeneralSettingValue, } from "~/atoms/settings/general" import { useProxyValue, useSetProxy } from "~/hooks/biz/useProxySetting" +import { useMinimizeToTrayValue, useSetMinimizeToTray } from "~/hooks/biz/useTraySetting" import { fallbackLanguage } from "~/i18n" import { tipcClient } from "~/lib/client" -import { SettingDescription, SettingInput } from "../control" +import { SettingDescription, SettingInput, SettingSwitch } from "../control" import { createSetting } from "../helper/builder" import { SettingItemGroup } from "../section" @@ -64,6 +65,7 @@ export const SettingGeneral = () => { saveLoginSetting(value) }, }), + IN_ELECTRON && MinimizeToTraySetting, LanguageSelector, { type: "title", @@ -231,3 +233,20 @@ const NettingSetting = () => { ) } + +const MinimizeToTraySetting = () => { + const { t } = useTranslation("settings") + const minimizeToTray = useMinimizeToTrayValue() + const setMinimizeToTray = useSetMinimizeToTray() + return ( + + + {t("general.minimize_to_tray.description")} + + ) +} diff --git a/changelog/next.md b/changelog/next.md index 8aa53a62f..2b0a17f93 100644 --- a/changelog/next.md +++ b/changelog/next.md @@ -5,6 +5,7 @@ - Feed owners can now reset their feeds. - Now you can export the data from the local database. - App: In consideration of your hard drive, now it supports clearing cache and limiting the size of cache. +- Added a new feature to allow minimizing to the system tray by enabling a switch in the settings. ## Improvements diff --git a/locales/errors/en.json b/locales/errors/en.json index 01498b8c2..1bbc4bf88 100644 --- a/locales/errors/en.json +++ b/locales/errors/en.json @@ -1,7 +1,6 @@ { "1": "Previous operation is not completed", "2": "CSRF Token mismatch", - "3": "Unprocessable content", "1000": "Unauthorized", "1001": "create session failed", "1002": "Invalid parameter", @@ -51,6 +50,5 @@ "10001": "Inbox already exists", "10002": "Inbox limit exceeded", "10003": "Inbox permission denied", - "11000": "RSSHub route not found", - "12000": "Action limit exceeded" + "11000": "RSSHub route not found" } diff --git a/locales/native/en.json b/locales/native/en.json index d5e9e681c..b26e489bf 100644 --- a/locales/native/en.json +++ b/locales/native/en.json @@ -42,6 +42,7 @@ "menu.hide": "Hide {{name}}", "menu.hideOthers": "Hide Others", "menu.minimize": "Minimize", + "menu.open": "Open {{name}}", "menu.openLogFile": "Open log file", "menu.paste": "Paste", "menu.pasteAndMatchStyle": "Paste and Match Style", diff --git a/locales/native/zh-CN.json b/locales/native/zh-CN.json index 4891854d2..4d6ba0e69 100644 --- a/locales/native/zh-CN.json +++ b/locales/native/zh-CN.json @@ -42,6 +42,7 @@ "menu.hide": "隐藏 {{name}}", "menu.hideOthers": "隐藏其他", "menu.minimize": "最小化", + "menu.open": "打开 {{name}}", "menu.openLogFile": "打开日志文件", "menu.paste": "粘贴", "menu.pasteAndMatchStyle": "粘贴并匹配样式", diff --git a/locales/settings/en.json b/locales/settings/en.json index 43d99d764..093673589 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -126,6 +126,8 @@ "general.mark_as_read.render.label": "Mark as read when in the view", "general.mark_as_read.scroll.description": "Automatically mark entries as read when scrolled out of the view.", "general.mark_as_read.scroll.label": "Mark as read when scrolling", + "general.minimize_to_tray.description": "Minimize to system tray when closing window", + "general.minimize_to_tray.label": "Minimize to tray", "general.network": "Network", "general.privacy": "Privacy", "general.proxy.description": "Set proxy for network traffic routing, e.g., socks://proxy.example.com:1080", diff --git a/locales/settings/zh-CN.json b/locales/settings/zh-CN.json index 77228575c..303c3145e 100644 --- a/locales/settings/zh-CN.json +++ b/locales/settings/zh-CN.json @@ -116,6 +116,8 @@ "general.mark_as_read.render.label": "在窗口中时标记为已读", "general.mark_as_read.scroll.description": "当条目滚动出窗口时自动标记为已读", "general.mark_as_read.scroll.label": "滚动时标记为已读", + "general.minimize_to_tray.description": "关闭窗口时最小化到系统托盘", + "general.minimize_to_tray.label": "最小化到托盘", "general.network": "网络", "general.proxy.description": "代理网络请求,示例:socks://proxy.example.com:1080", "general.proxy.label": "代理", diff --git a/resources/tray-icon.png b/resources/tray-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..edb10a250ac54d7b108a10c34e221204d22e54a3 GIT binary patch literal 431 zcmV;g0Z{&lP)Px$X-PyuR9HvNmrZiRAPj{c*XpLt5xVCX-8WwM8eaDbbrwArwN&t6nphHG*Ir~M z2}U2%(+>{C6FgqxPw(Y_jo)toCO2Zr_i_1`;Bf`e+i=M}xRLGfvj7B-ubD8NzVWc~ z>u&tD%^wGyyriOVToOQ#nRi)nalzvaz{f7z%bQN80Qdy(D#Pxwf<2%Gp!}s2TIKN; zR`8tClvxk6OAV0H#_ESy*eJ#CK3ah53@})Yr}bMkMhn0>+W_z|&9wkzo66_Sr~!(7 z(m_)QY7Z~Ir||%(UZeb_!H8C~1rmT-e3II0vp@|Ho0_?!cJn|4FgG;`fa9;J0kP_t zbsz!cq1zH-^&n#bxThn6sy5COk)avo04s6M?l;FiZB_+PHl~(&vKIiATeASq5CYRc zvWEy6;0eIDrG9r@JN!4maxXaIN>)0KuW0AEnq{-w5uR9$cdOfR>}Y9>e(or?wAG)n Z{s#mRl~iy5#-IQI002ovPDHLkV1oL_!3O{U literal 0 HcmV?d00001