import isInputElement from "./is-input-element" ; import isInputEvent from "./is-input-event" ; import isEventModifier from "./is-event-modifier" ; import getKeyEventName from "./get-key-event-name" ; import { getBus , MinibusCallback , MinibusUnsubscriber , } from "@jiveworld/minibus" ; const defaultMonitor = ( eventName ) => { console . log ( ":keyboard event:" , eventName ) ; } ; export type KeyboardEvent = "keydown" | "keyup" ; export interface KeyboardistListener { subscribe : ( name : string , callback : MinibusCallback ) => MinibusUnsubscriber ; setMonitor : ( monitor ? : MinibusCallback | Boolean ) => void ; startListening : ( ) => void ; stopListening : ( ) => void ; } export function createListener ( listenForEvent = "keydown" , element = null ) { const bus = getBus ( "@minibus/" + listenForEvent ) ; if ( typeof window === "undefined" ) { return false ; } if ( element === null ) { element = window . document ; } const ignoreInputEvents = ! isInputElement ( element ) ; function normalize ( eventName ) { return eventName . toLowerCase ( ) . replace ( /\s/ , "" ) ; } function handleKeyEvent ( event ) { if ( isEventModifier ( event ) ) { return ; } if ( ignoreInputEvents && isInputEvent ( event ) ) { return ; } const eventName = normalize ( getKeyEventName ( event ) ) ; const noEvents = bus . isChannelEmpty ( eventName ) ; bus . emit ( "monitor" , eventName , ! noEvents , event ) ; bus . emit ( eventName , event ) ; } function subscribe ( name , callback ) { const subscription = bus . subscribe ( normalize ( name ) , ( event ) => { event . preventDefault ( ) ; callback ( ) ; } ) ; return subscription ; } function setMonitor ( monitor = false ) { if ( monitor === true ) { bus . subscribe ( "monitor" , defaultMonitor ) ; } else if ( typeof monitor === "function" ) { bus . subscribe ( "monitor" , monitor ) ; } } function startListening ( ) { if ( element ) { element . addEventListener ( listenForEvent , handleKeyEvent ) ; } } function stopListening ( ) { if ( element ) { element . removeEventListener ( listenForEvent , handleKeyEvent ) ; } } startListening ( ) ; return { subscribe , setMonitor , startListening , stopListening } ; }