jan/electron/utils/selectedText.ts
Van Pham aa1f01f4fa
Revert "chore: remove nutjs" and replace nutjs version (#2900)
* Revert "chore: remove nutjs (#2860)"

This reverts commit ce2d8e540582a73423efed02dbe484e213cdf0fe.

* feat: change nut-js to download from GitHub

* feat: change nut-js to use @nut-tree-fork/nut-js

* Revert "Chore: temporary disable cache for server migration (#2742)"

This reverts commit af9a35110ba2462279dfb988cc89748697a97899.

* feat: disable quickask settings on linux

* feat: enable quick ask linux again

* Change to @kirillvakalov/nut-tree__nut-js (#2906)

Co-authored-by: Hien To <tominhhien97@gmail.com>

---------

Co-authored-by: Van-QA <van@jan.ai>
Co-authored-by: hiento09 <136591877+hiento09@users.noreply.github.com>
Co-authored-by: Hien To <tominhhien97@gmail.com>
2024-05-15 15:03:29 +07:00

45 lines
1.5 KiB
TypeScript

import { clipboard, globalShortcut } from 'electron'
import { keyboard, Key } from "@kirillvakalov/nut-tree__nut-js"
/**
* Gets selected text by synthesizing the keyboard shortcut
* "CommandOrControl+c" then reading text from the clipboard
*/
export const getSelectedText = async () => {
const currentClipboardContent = clipboard.readText() // preserve clipboard content
clipboard.clear()
const hotkeys: Key[] = [
process.platform === 'darwin' ? Key.LeftCmd : Key.LeftControl,
Key.C,
]
await keyboard.pressKey(...hotkeys)
await keyboard.releaseKey(...hotkeys)
await new Promise((resolve) => setTimeout(resolve, 200)) // add a delay before checking clipboard
const selectedText = clipboard.readText()
clipboard.writeText(currentClipboardContent)
return selectedText
}
/**
* Registers a global shortcut of `accelerator`. The `callback` is called
* with the selected text when the registered shortcut is pressed by the user
*
* Returns `true` if the shortcut was registered successfully
*/
export const registerShortcut = (
accelerator: Electron.Accelerator,
callback: (selectedText: string) => void
) => {
return globalShortcut.register(accelerator, async () => {
callback(await getSelectedText())
})
}
/**
* Unregisters a global shortcut of `accelerator` and
* is equivalent to electron.globalShortcut.unregister
*/
export const unregisterShortcut = (accelerator: Electron.Accelerator) => {
globalShortcut.unregister(accelerator)
}