feat: support Electron native search page content (#198)

* init

Signed-off-by: Innei <i@innei.in>

* feat: native search

Signed-off-by: Innei <i@innei.in>

* fix: color in light

Signed-off-by: Innei <i@innei.in>

* fix: add shadow

Signed-off-by: Innei <i@innei.in>

---------

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-08-04 02:03:57 +08:00
committed by GitHub
parent b6158ec0bd
commit 29b67dcf1b
15 changed files with 472 additions and 47 deletions
+10 -1
View File
@@ -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"
-6
View File
@@ -1,6 +0,0 @@
let shouldAppDoHide = process.platform === "darwin"
export const getShouldAppDoHide = () => shouldAppDoHide
export const setShouldAppDoHide = (value: boolean) => {
shouldAppDoHide = value
}
+2 -2
View File
@@ -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()
}
})
+86 -27
View File
@@ -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<MenuItemConstructorOptions | MenuItem> = [
{
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()
},
},
],
})
}
+24
View File
@@ -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<Electron.Result | null>()
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
+1 -1
View File
@@ -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 = {
+8 -4
View File
@@ -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<GithubUpdateInfo> {
resolveFiles(updateInfo: GithubUpdateInfo): Array<ResolvedUpdateFileInfo> {
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
+2 -4
View File
@@ -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")
+14 -2
View File
@@ -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
}
@@ -56,5 +56,6 @@ export const useInputComposition = (
onCompositionEnd: handleCompositionEnd,
onCompositionStart: handleCompositionStart,
onKeyDown: handleKeyDown,
isCompositionRef,
}
}
+79
View File
@@ -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<Element, Array<ObserveResize>>();
// 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
}
+242
View File
@@ -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<HTMLInputElement>(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<number>(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 (
<form
onSubmit={(e) => {
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"
>
<div className="relative h-full grow">
<input
{...inputProps}
ref={inputRef}
name="search"
className="absolute inset-0 size-full appearance-none bg-transparent font-[system-ui] text-[15px]"
style={{
visibility: isSearching ? "hidden" : "visible",
}}
type="text"
value={value}
onChange={async (e) => {
e.preventDefault()
const search = e.target.value
setValue(search)
setIsSearching(false)
nativeSearch(search)
}}
/>
<CanvasText
className={cn(
"pointer-events-none absolute inset-0 size-full text-transparent [&::placeholder]:text-foreground",
isSearching ? "visible" : "invisible",
)}
text={value}
/>
</div>
<div className="center gap-1 [&>*]:opacity-80">
<button
type="button"
className="center hover:opacity-90"
onClick={() => {
nativeSearchImpl(value, "backward")
}}
>
<i className="i-mgc-back-2-cute-re" />
</button>
<button
type="button"
className="center hover:opacity-90"
onClick={() => {
nativeSearchImpl(value, "forward")
}}
>
<i className="i-mgc-forward-2-cute-re" />
</button>
<button
type="button"
className="center hover:opacity-90"
onClick={() => {
setValue("")
nativeSearchImpl("")
onClose()
}}
>
<i className="i-mingcute-close-circle-fill" />
</button>
</div>
</form>
)
}
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<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = ref.current
if (!canvas) {
return
}
drawText(canvas, text)
return observeResize(canvas, () => drawText(canvas, text))
}, [text])
return <canvas className={className} ref={ref} />
}
export const CmdF = () => {
const [show, setShow] = useState(false)
useSubscribeElectronEvent("OpenSearch", () => {
setShow(true)
})
return (
<AnimatePresence>
{show && (
<m.div
initial={{ opacity: 0.8, y: -150 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -150 }}
transition={softSpringPreset}
>
<CmdFImpl
onClose={() => {
setShow(false)
}}
/>
</m.div>
)}
</AnimatePresence>
)
}
+2
View File
@@ -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() {
<SearchCmdK />
<CmdNTrigger />
{ELECTRON && <CmdF />}
{isAuthFail && !user && (
<RootPortal>
<DeclarativeModal
+1
View File
@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react"
export const EventsMap = {
QuickAdd: "quick-add",
Discover: "discover",
OpenSearch: "open-search",
}
export const dispatchEventOnWindow = (