diff options
author | Andrey Tyrin <andrei.tyrin@jetbrains.com> | 2022-08-25 00:44:21 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-08-25 01:44:21 +0300 |
commit | 56beaa318c603c0ada0cf97454f06fbb44175917 (patch) | |
tree | 07fe058a94346cbb5a4404659f31f4b02489f1bb /plugins/base/frontend/src/main/components/utils/hotkey.ts | |
parent | ce1998247e0478a9d22860026efb9694e2916396 (diff) | |
download | dokka-56beaa318c603c0ada0cf97454f06fbb44175917.tar.gz dokka-56beaa318c603c0ada0cf97454f06fbb44175917.tar.bz2 dokka-56beaa318c603c0ada0cf97454f06fbb44175917.zip |
Add hotkey for opening search dialog (#2633)
Diffstat (limited to 'plugins/base/frontend/src/main/components/utils/hotkey.ts')
-rw-r--r-- | plugins/base/frontend/src/main/components/utils/hotkey.ts | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/plugins/base/frontend/src/main/components/utils/hotkey.ts b/plugins/base/frontend/src/main/components/utils/hotkey.ts new file mode 100644 index 00000000..8ba47ab5 --- /dev/null +++ b/plugins/base/frontend/src/main/components/utils/hotkey.ts @@ -0,0 +1,58 @@ +import {detectOsKind, OsKind} from "./os"; + +type ModifierKey = { + name: string + keyArg: string +} + +class ModifierKeys { + static metaKey: ModifierKey = {name: "Command", keyArg: "Meta"} + static ctrlKey: ModifierKey = {name: "Ctrl", keyArg: "Control"} + static altKey: ModifierKey = {name: "Alt", keyArg: "Alt"} + static shiftKey: ModifierKey = {name: "Shift", keyArg: "Shift"} +} + +const setOfKeys = [ModifierKeys.altKey, ModifierKeys.shiftKey, ModifierKeys.ctrlKey, ModifierKeys.metaKey] + +export class Hotkey { + private readonly osKind: OsKind; + + constructor() { + this.osKind = detectOsKind() + } + + public getOsAccelKeyName() { + return this.getOsAccelKey().name + } + + /** + * Register a hotkey of combination Accel key (Cmd/Ctrl depending on OS). + * The method also checks that other modifiers key is not pressed to avoid shortcuts intersection. + * E.g. don't trigger [Ctrl+K] if [Ctrl + Shift + K] pressed + */ + public registerHotkeyWithAccel = (event: () => void, letter: string) => { + const osMetaKey = this.getOsAccelKey() + document.onkeydown = (keyDownEvent) => { + const isMetaKeyPressed = keyDownEvent.getModifierState(osMetaKey.keyArg) + const isOtherModifierKeyPressed = setOfKeys + .filter(key => key !== osMetaKey) + .map((otherKeys: ModifierKey) => keyDownEvent.getModifierState(otherKeys.keyArg)) + .some(value => value) + + if (isMetaKeyPressed && !isOtherModifierKeyPressed && keyDownEvent.key === letter) { + keyDownEvent.preventDefault() + event() + } + }; + } + + private getOsAccelKey(): ModifierKey { + switch (this.osKind) { + case OsKind.MACOS: + return ModifierKeys.metaKey + default: + return ModifierKeys.ctrlKey + } + } +} + |