aboutsummaryrefslogtreecommitdiff
path: root/plugins/base/frontend/src/main/components/utils
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/base/frontend/src/main/components/utils')
-rw-r--r--plugins/base/frontend/src/main/components/utils/hotkey.ts58
-rw-r--r--plugins/base/frontend/src/main/components/utils/os.ts14
2 files changed, 72 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
+ }
+ }
+}
+
diff --git a/plugins/base/frontend/src/main/components/utils/os.ts b/plugins/base/frontend/src/main/components/utils/os.ts
new file mode 100644
index 00000000..3005245c
--- /dev/null
+++ b/plugins/base/frontend/src/main/components/utils/os.ts
@@ -0,0 +1,14 @@
+export enum OsKind{
+ WINDOWS,
+ MACOS,
+ LINUX,
+ OTHER
+}
+
+export const detectOsKind = (): OsKind => {
+ const userAgent = navigator.userAgent
+ if(userAgent.includes("Mac")) return OsKind.MACOS
+ else if (userAgent.includes("Win")) return OsKind.WINDOWS
+ else if (userAgent.includes("Linux")) return OsKind.LINUX
+ else return OsKind.OTHER
+} \ No newline at end of file