Created
December 18, 2020 03:40
-
-
Save liuwenzhuang/b8505b67988f553b5e900205af421c7d to your computer and use it in GitHub Desktop.
rxjs-keyboard-event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { fromEvent, of, EMPTY } from 'rxjs'; | |
import { switchMap } from 'rxjs/operators'; | |
import { isEmpty } from 'lodash'; | |
function bindKeyboardShortcuts(eventName: string, keybinding: string) { | |
const keys = keybinding.split('.').map(key => key.toLowerCase()); | |
const allModifierKeys = ['ctrl', 'shift', 'alt', 'cmd', 'meta']; // meta === cmd | |
const modifierKeys = keys.filter(key => allModifierKeys.indexOf(key) !== -1); | |
return fromEvent(document, eventName).pipe( | |
switchMap((e: KeyboardEvent) => { | |
if (!isEmpty(modifierKeys)) { | |
// 判断对应的功能按键是否存在 | |
const flag = modifierKeys.every(key => { | |
switch (key) { | |
case 'ctrl': | |
return e.ctrlKey; | |
case 'shift': | |
return e.shiftKey; | |
case 'alt': | |
return e.altKey; | |
case 'cmd': | |
case 'meta': | |
return e.metaKey; | |
default: | |
return false; | |
} | |
}); | |
if (!flag) { | |
return EMPTY; | |
} | |
} | |
const eventKey = e.key.toLowerCase(); | |
if (keys.indexOf(eventKey) === -1) { | |
return EMPTY; | |
} | |
return of(e); | |
}) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment