Added back keyboard handlers

This commit is contained in:
squidfunk
2021-02-12 16:41:33 +01:00
parent 44751785a0
commit e7850ca184
13 changed files with 177 additions and 37 deletions

View File

@@ -23,20 +23,33 @@
import { Observable, fromEvent } from "rxjs"
import { filter, map, share } from "rxjs/operators"
import { getActiveElement } from "../element"
import { getToggle } from "../toggle"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Key
* Keyboard mode
*/
export interface Key {
export type KeyboardMode =
| "global" /* Global */
| "search" /* Search is open */
/* ------------------------------------------------------------------------- */
/**
* Keyboard
*/
export interface Keyboard {
mode: KeyboardMode /* Keyboard mode */
type: string /* Key type */
claim(): void /* Key claim */
}
/* ----------------------------------------------------------------------------
* Functions
* Helper functions
* ------------------------------------------------------------------------- */
/**
@@ -46,7 +59,7 @@ export interface Key {
*
* @returns Test result
*/
export function isSusceptibleToKeyboard(el: HTMLElement): boolean {
function isSusceptibleToKeyboard(el: HTMLElement): boolean {
switch (el.tagName) {
/* Form elements */
@@ -61,24 +74,35 @@ export function isSusceptibleToKeyboard(el: HTMLElement): boolean {
}
}
/* ------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Watch keyboard
*
* @returns Keyboard observable
*/
export function watchKeyboard(): Observable<Key> {
export function watchKeyboard(): Observable<Keyboard> {
return fromEvent<KeyboardEvent>(window, "keydown")
.pipe(
filter(ev => !(ev.metaKey || ev.ctrlKey)),
map(ev => ({
mode: getToggle("search") ? "search" : "global",
type: ev.key,
claim() {
ev.preventDefault()
ev.stopPropagation()
}
})),
} as Keyboard)),
filter(({ mode }) => {
if (mode === "global") {
const active = getActiveElement()
if (typeof active !== "undefined")
return !isSusceptibleToKeyboard(active)
}
return true
}),
share()
)
}