From 29b67dcf1b1c1c41b4b4d6be5df4dcfade6c31f5 Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 4 Aug 2024 02:03:57 +0800 Subject: [PATCH] feat: support Electron native search page content (#198) * init Signed-off-by: Innei * feat: native search Signed-off-by: Innei * fix: color in light Signed-off-by: Innei * fix: add shadow Signed-off-by: Innei --------- Signed-off-by: Innei --- src/main/env.ts | 11 +- src/main/flag.ts | 6 - src/main/index.ts | 4 +- src/main/lib/{until.ts => utils.ts} | 0 src/main/menu.ts | 113 ++++++-- src/main/tipc/app.ts | 24 ++ src/main/tipc/dock.ts | 2 +- src/main/updater/custom-github-provider.ts | 12 +- src/main/updater/index.ts | 6 +- src/main/window.ts | 16 +- .../src/hooks/common/useInputComposition.ts | 1 + src/renderer/src/lib/observe-resize.ts | 79 ++++++ src/renderer/src/modules/panel/cmdf.tsx | 242 ++++++++++++++++++ src/renderer/src/pages/(main)/layout.tsx | 2 + src/shared/src/event.ts | 1 + 15 files changed, 472 insertions(+), 47 deletions(-) delete mode 100644 src/main/flag.ts rename src/main/lib/{until.ts => utils.ts} (100%) create mode 100644 src/renderer/src/lib/observe-resize.ts create mode 100644 src/renderer/src/modules/panel/cmdf.tsx diff --git a/src/main/env.ts b/src/main/env.ts index 62d226135..2c0727bbb 100644 --- a/src/main/env.ts +++ b/src/main/env.ts @@ -4,4 +4,13 @@ import * as semver from "semver" export const mode = process.env.NODE_ENV export const isDev = mode === "development" -export const channel = isDev ? "development" : ((semver.prerelease(app.getVersion())?.[0] as string) || "stable") +export const channel = isDev ? + "development" : + (semver.prerelease(app.getVersion())?.[0] as string) || "stable" + +const { platform } = process +export const isMacOS = platform === "darwin" + +export const isWindows = platform === "win32" + +export const isLinux = platform === "linux" diff --git a/src/main/flag.ts b/src/main/flag.ts deleted file mode 100644 index 67c106be8..000000000 --- a/src/main/flag.ts +++ /dev/null @@ -1,6 +0,0 @@ -let shouldAppDoHide = process.platform === "darwin" - -export const getShouldAppDoHide = () => shouldAppDoHide -export const setShouldAppDoHide = (value: boolean) => { - shouldAppDoHide = value -} diff --git a/src/main/index.ts b/src/main/index.ts index df9ca3567..9fb1e13ce 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -7,7 +7,7 @@ import { app, BrowserWindow, session } from "electron" import squirrelStartup from "electron-squirrel-startup" import { env } from "../env" -import { isDev } from "./env" +import { isDev, isMacOS } from "./env" import { initializationApp } from "./init" import { setAuthSessionToken } from "./lib/user" import { registerUpdater } from "./updater" @@ -145,7 +145,7 @@ function bootsharp() { // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on("window-all-closed", () => { - if (process.platform !== "darwin") { + if (!isMacOS) { app.quit() } }) diff --git a/src/main/lib/until.ts b/src/main/lib/utils.ts similarity index 100% rename from src/main/lib/until.ts rename to src/main/lib/utils.ts diff --git a/src/main/menu.ts b/src/main/menu.ts index de42b904d..db7358702 100644 --- a/src/main/menu.ts +++ b/src/main/menu.ts @@ -3,36 +3,43 @@ import { dispatchEventOnWindow } from "@shared/event" import type { MenuItem, MenuItemConstructorOptions } from "electron" import { Menu } from "electron" +import { isDev, isMacOS } from "./env" import { revealLogFile } from "./logger" +import { checkForUpdates, quitAndInstall } from "./updater" import { createSettingWindow, createWindow, getMainWindow } from "./window" export const registerAppMenu = () => { const menus: Array = [ - { - role: "appMenu", - submenu: [ - { - type: "normal", - label: `About ${name}`, - click: () => { - createSettingWindow("about") + ...(isMacOS ? + ([ + { + label: name, + submenu: [ + { + type: "normal", + label: `About ${name}`, + click: () => { + createSettingWindow("about") + }, + }, + { type: "separator" }, + { + label: "Settings...", + accelerator: "CmdOrCtrl+,", + click: () => createSettingWindow(), + }, + { type: "separator" }, + { role: "services" }, + { type: "separator" }, + { role: "hide" }, + { role: "hideOthers" }, + { type: "separator" }, + { role: "quit" }, + ], }, - }, - { type: "separator" }, - { - label: "Settings...", - accelerator: "CmdOrCtrl+,", - click: () => createSettingWindow(), - }, - { type: "separator" }, - { role: "services" }, - { type: "separator" }, - { role: "hide" }, - { role: "hideOthers" }, - { type: "separator" }, - { role: "quit" }, - ], - }, + ] as MenuItemConstructorOptions[]) : + []), + { role: "fileMenu", submenu: [ @@ -64,8 +71,46 @@ export const registerAppMenu = () => { { role: "close" }, ], }, - { role: "editMenu" }, - { role: "viewMenu" }, + { + label: "Edit", + submenu: [ + { role: "undo" }, + { role: "redo" }, + { type: "separator" }, + { role: "cut" }, + { role: "copy" }, + { role: "paste" }, + { type: "separator" }, + { + type: "normal", + label: "Search", + accelerator: "CmdOrCtrl+F", + click(_e, window) { + if (!window) return + dispatchEventOnWindow(window, "OpenSearch") + }, + }, + ...((isMacOS ? + [ + { role: "pasteAndMatchStyle" }, + { role: "delete" }, + { role: "selectAll" }, + { type: "separator" }, + { + label: "Speech", + submenu: [{ role: "startSpeaking" }, { role: "stopSpeaking" }], + }, + ] : + [ + { role: "delete" }, + { type: "separator" }, + { role: "selectAll" }, + ]) as MenuItemConstructorOptions[]), + ], + }, + { + role: "viewMenu", + }, { role: "windowMenu" }, { role: "help", @@ -76,11 +121,18 @@ export const registerAppMenu = () => { await revealLogFile() }, }, + { + label: "Check for Updates", + click: async () => { + getMainWindow()?.show() + await checkForUpdates() + }, + }, ], }, ] - if (import.meta.env.DEV) { + if (isDev) { menus.push({ label: "Debug", submenu: [ @@ -96,6 +148,13 @@ export const registerAppMenu = () => { }) }, }, + { + type: "normal", + label: "Debug: Quit and Install Update", + click() { + quitAndInstall() + }, + }, ], }) } diff --git a/src/main/tipc/app.ts b/src/main/tipc/app.ts index 0362ca982..26736fff4 100644 --- a/src/main/tipc/app.ts +++ b/src/main/tipc/app.ts @@ -85,6 +85,30 @@ export const appRoute = { /// clipboard readClipboard: t.procedure.action(async () => clipboard.readText()), + /// search + search: t.procedure + .input<{ + text: string + options: Electron.FindInPageOptions + }>() + .action(async ({ input, context }) => { + const { sender: webContents } = context + + const { promise, resolve } = + Promise.withResolvers() + + let requestId = -1 + webContents.once("found-in-page", (_, result) => { + resolve(result.requestId === requestId ? result : null) + }) + requestId = webContents.findInPage(input.text, input.options) + return promise + }), + clearSearch: t.procedure.action(async ({ + context: { sender: webContents }, + }) => { + webContents.stopFindInPage("keepSelection") + }), } interface Sender extends Electron.WebContents { getOwnerBrowserWindow: () => Electron.BrowserWindow | null diff --git a/src/main/tipc/dock.ts b/src/main/tipc/dock.ts index 4767059f3..3ad5ff65c 100644 --- a/src/main/tipc/dock.ts +++ b/src/main/tipc/dock.ts @@ -1,7 +1,7 @@ import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../constants/app" import { apiClient } from "../lib/api-client" import { setDockCount } from "../lib/dock" -import { sleep } from "../lib/until" +import { sleep } from "../lib/utils" import { t } from "./_instance" const timerMap = { diff --git a/src/main/updater/custom-github-provider.ts b/src/main/updater/custom-github-provider.ts index 27a5ce817..425a84436 100644 --- a/src/main/updater/custom-github-provider.ts +++ b/src/main/updater/custom-github-provider.ts @@ -25,6 +25,8 @@ import { } from "electron-updater/out/providers/Provider" import * as semver from "semver" +import { isWindows } from "../env" + interface GithubUpdateInfo extends UpdateInfo { tag: string } @@ -258,12 +260,14 @@ export class CustomGitHubProvider extends BaseGitHubProvider { resolveFiles(updateInfo: GithubUpdateInfo): Array { const filteredUpdateInfo = structuredClone(updateInfo) // for windows, we need to determine its installer type (nsis or squirrel) - if (process.platform === "win32" && updateInfo.files.length > 1) { + if (isWindows && updateInfo.files.length > 1) { const isSquirrel = isSquirrelBuild() // @ts-expect-error we should be able to modify the object - filteredUpdateInfo.files = updateInfo.files.filter((file) => isSquirrel ? - !file.url.includes("nsis.exe") : - file.url.includes("nsis.exe")) + filteredUpdateInfo.files = updateInfo.files.filter((file) => + isSquirrel ? + !file.url.includes("nsis.exe") : + file.url.includes("nsis.exe"), + ) } // still replace space to - due to backward compatibility diff --git a/src/main/updater/index.ts b/src/main/updater/index.ts index c6209d7b9..ac7efe364 100644 --- a/src/main/updater/index.ts +++ b/src/main/updater/index.ts @@ -2,22 +2,20 @@ import { getRendererHandlers } from "@egoist/tipc/main" import { autoUpdater } from "electron-updater" import { channel, isDev } from "../env" -import { setShouldAppDoHide } from "../flag" import { trackEvent } from "../lib/posthog" import { logger } from "../logger" import type { RendererHandlers } from "../renderer-handlers" -import { getMainWindow } from "../window" +import { destroyMainWindow, getMainWindow } from "../window" import { CustomGitHubProvider } from "./custom-github-provider" // skip auto update in dev mode const disabled = isDev export const quitAndInstall = async () => { - setShouldAppDoHide(false) const mainWindow = getMainWindow() + destroyMainWindow() logger.info("Quit and install update, close main window, ", mainWindow?.id) - mainWindow?.close() setTimeout(() => { logger.info("Window is closed, quit and install update") diff --git a/src/main/window.ts b/src/main/window.ts index 422d4cb4c..6571649bf 100644 --- a/src/main/window.ts +++ b/src/main/window.ts @@ -6,7 +6,7 @@ import { callGlobalContextMethod } from "@shared/bridge" import type { BrowserWindowConstructorOptions } from "electron" import { BrowserWindow, Menu, shell } from "electron" -import { getShouldAppDoHide } from "./flag" +import { isMacOS } from "./env" import { getIconPath } from "./helper" import { store } from "./lib/store" import { logger } from "./logger" @@ -195,7 +195,7 @@ export const createMainWindow = () => { windows.mainWindow = window window.on("close", (event) => { - if (process.platform === "darwin" && getShouldAppDoHide()) { + if (isMacOS) { event.preventDefault() window.hide() } else { @@ -246,3 +246,15 @@ export const createSettingWindow = (path?: string) => { } export const getMainWindow = () => windows.mainWindow + +export const getMainWindowOrCreate = () => { + if (!windows.mainWindow) { + createMainWindow() + } + return windows.mainWindow +} + +export const destroyMainWindow = () => { + windows.mainWindow?.destroy() + windows.mainWindow = null +} diff --git a/src/renderer/src/hooks/common/useInputComposition.ts b/src/renderer/src/hooks/common/useInputComposition.ts index 44546954a..cd9929dc5 100644 --- a/src/renderer/src/hooks/common/useInputComposition.ts +++ b/src/renderer/src/hooks/common/useInputComposition.ts @@ -56,5 +56,6 @@ export const useInputComposition = ( onCompositionEnd: handleCompositionEnd, onCompositionStart: handleCompositionStart, onKeyDown: handleKeyDown, + isCompositionRef, } } diff --git a/src/renderer/src/lib/observe-resize.ts b/src/renderer/src/lib/observe-resize.ts new file mode 100644 index 000000000..4d77b1070 --- /dev/null +++ b/src/renderer/src/lib/observe-resize.ts @@ -0,0 +1,79 @@ +/** + * @see https://github.com/toeverything/AFFiNE/blob/98e35384a6f71bf64c668b8f13afcaf28c9b8e97/packages/frontend/component/src/utils/observe-resize.ts + * @copyright AFFiNE + */ +type ObserveResize = { + callback: (entity: ResizeObserverEntry) => void + dispose: () => void +} + +let _resizeObserver: ResizeObserver | null = null +const elementsMap = new WeakMap>(); + +// for debugging +(window as any)._resizeObserverElementsMap = elementsMap + +/** + * @internal get or initialize the ResizeObserver instance + */ +const getResizeObserver = () => + (_resizeObserver ??= new ResizeObserver((entries) => { + entries.forEach((entry) => { + const listeners = elementsMap.get(entry.target) ?? [] + listeners.forEach(({ callback }) => callback(entry)) + }) + })) + +/** + * @internal remove element's specific listener + */ +const removeListener = (element: Element, listener: ObserveResize) => { + if (!element) return + const listeners = elementsMap.get(element) ?? [] + const observer = getResizeObserver() + // remove the listener from the element + if (listeners.includes(listener)) { + elementsMap.set( + element, + listeners.filter((l) => l !== listener), + ) + } + // if no more listeners, unobserve the element + if (elementsMap.get(element)?.length === 0) { + observer.unobserve(element) + elementsMap.delete(element) + } +} + +/** + * A function to observe the resize of an element use global ResizeObserver. + * + * ```ts + * useEffect(() => { + * const dispose1 = observeResize(elRef1.current, (entry) => {}); + * const dispose2 = observeResize(elRef2.current, (entry) => {}); + * + * return () => { + * dispose1(); + * dispose2(); + * }; + * }, []) + * ``` + * @return A function to dispose the observer. + */ +export const observeResize = ( + element: Element, + callback: ObserveResize["callback"], +) => { + const observer = getResizeObserver() + if (!elementsMap.has(element)) { + observer.observe(element) + } + const prevListeners = elementsMap.get(element) ?? [] + const listener = { callback, dispose: () => {} } + listener.dispose = () => removeListener(element, listener) + + elementsMap.set(element, [...prevListeners, listener]) + + return listener.dispose +} diff --git a/src/renderer/src/modules/panel/cmdf.tsx b/src/renderer/src/modules/panel/cmdf.tsx new file mode 100644 index 000000000..f2c6337a3 --- /dev/null +++ b/src/renderer/src/modules/panel/cmdf.tsx @@ -0,0 +1,242 @@ +/** + * @see https://github.com/toeverything/AFFiNE/blob/98e35384a6f71bf64c668b8f13afcaf28c9b8e97/packages/frontend/core/src/modules/find-in-page/view/find-in-page-modal.tsx + * @copyright AFFiNE, Follow + */ +import { softSpringPreset } from "@renderer/components/ui/constants/spring" +import { useInputComposition, useRefValue } from "@renderer/hooks/common" +import { tipcClient } from "@renderer/lib/client" +import { nextFrame } from "@renderer/lib/dom" +import { observeResize } from "@renderer/lib/observe-resize" +import { cn } from "@renderer/lib/utils" +import { useSubscribeElectronEvent } from "@shared/event" +import { AnimatePresence, m } from "framer-motion" +import type { FC } from "react" +import { useEffect, useLayoutEffect, useRef, useState } from "react" +import { useDebounceCallback, useEventCallback } from "usehooks-ts" + +const CmdFImpl: FC<{ + onClose: () => void +}> = ({ onClose }) => { + const [value, setValue] = useState("") + + const currentValue = useRefValue(value) + const inputRef = useRef(null) + useLayoutEffect(() => { + tipcClient?.readClipboard().then((text) => { + if (!currentValue.current) { + setValue(text) + } + }) + + inputRef.current?.focus() + // Select all + + nextFrame(() => + inputRef.current?.setSelectionRange(0, currentValue.current.length), + ) + }, [currentValue]) + + const [isSearching, setIsSearching] = useState(false) + + const searchIdRef = useRef(0) + + const { isCompositionRef, ...inputProps } = useInputComposition({ + onKeyDown: useEventCallback((e) => { + const $input = inputRef.current + if (!$input) return + + if (e.key === "Escape") { + nativeSearchImpl("") + onClose() + e.preventDefault() + } + }), + onCompositionEnd: useEventCallback(() => nativeSearch(value)), + }) + + const nativeSearchImpl = useEventCallback( + async ( + text: string, + + dir: "forward" | "backward" = "forward", + ) => { + if (isCompositionRef.current) return + setIsSearching(true) + + const searchId = ++searchIdRef.current + + let findNext = true + if (!text) { + await tipcClient?.clearSearch().finally(() => { + if (searchId === searchIdRef.current) { + setIsSearching(false) + } + }) + } else { + await tipcClient + ?.search({ + text, + options: { + findNext, + forward: dir === "forward", + }, + }) + .finally(() => { + if (searchId === searchIdRef.current) { + setIsSearching(false) + findNext = false + } + }) + } + }, + ) + const nativeSearch = useDebounceCallback(nativeSearchImpl, 500) + useLayoutEffect(() => { + inputRef.current?.focus() + setTimeout(() => { + inputRef.current?.focus() + }) + }, [isSearching]) + return ( +
{ + e.preventDefault() + nativeSearch(value) + }} + className="center shadow-perfect fixed right-8 top-12 z-[1000] size-9 w-64 gap-2 rounded-2xl border bg-zinc-50/90 pl-3 pr-2 backdrop-blur duration-200 focus-within:border-theme-accent dark:bg-neutral-800/80" + > +
+ { + e.preventDefault() + const search = e.target.value + setValue(search) + setIsSearching(false) + nativeSearch(search) + }} + /> + + +
+
+ + + +
+ + ) +} + +const drawText = (canvas: HTMLCanvasElement, text: string) => { + const ctx = canvas.getContext("2d") + if (!ctx) { + return + } + + const dpr = window.devicePixelRatio || 1 + canvas.width = canvas.getBoundingClientRect().width * dpr + canvas.height = canvas.getBoundingClientRect().height * dpr + + const rootStyles = getComputedStyle(document.documentElement) + + const textColor = `hsl(${rootStyles + .getPropertyValue("--foreground") + .trim()})` + + ctx.scale(dpr, dpr) + ctx.clearRect(0, 0, canvas.width, canvas.height) + ctx.fillStyle = textColor + ctx.font = "15px system-ui" + + ctx.fillText(text, 0, 22) + ctx.textAlign = "left" + ctx.textBaseline = "middle" +} + +const CanvasText = ({ + text, + className, +}: { + text: string + className: string +}) => { + const ref = useRef(null) + + useEffect(() => { + const canvas = ref.current + if (!canvas) { + return + } + drawText(canvas, text) + return observeResize(canvas, () => drawText(canvas, text)) + }, [text]) + + return +} + +export const CmdF = () => { + const [show, setShow] = useState(false) + + useSubscribeElectronEvent("OpenSearch", () => { + setShow(true) + }) + return ( + + {show && ( + + { + setShow(false) + }} + /> + + )} + + ) +} diff --git a/src/renderer/src/pages/(main)/layout.tsx b/src/renderer/src/pages/(main)/layout.tsx index 9da50e7f6..8073f41bc 100644 --- a/src/renderer/src/pages/(main)/layout.tsx +++ b/src/renderer/src/pages/(main)/layout.tsx @@ -14,6 +14,7 @@ import { LoginModalContent } from "@renderer/modules/auth/LoginModalContent" import { FeedColumn } from "@renderer/modules/feed-column" import { AutoUpdater } from "@renderer/modules/feed-column/auto-updater" import { CornerPlayer } from "@renderer/modules/feed-column/corner-player" +import { CmdF } from "@renderer/modules/panel/cmdf" import { SearchCmdK } from "@renderer/modules/panel/cmdk" import { CmdNTrigger } from "@renderer/modules/panel/cmdn" import type { PropsWithChildren } from "react" @@ -65,6 +66,7 @@ export function Component() { + {ELECTRON && } {isAuthFail && !user && (