2022-12-01 00:17:15 +01:00
import utils from "./utils.js" ;
2024-12-19 21:03:38 +02:00
type ElementType = HTMLElement | Document ;
2025-03-16 18:31:31 +02:00
type Handler = ( e : JQuery.TriggeredEvent < ElementType | Element , string , ElementType | Element , ElementType | Element > ) = > void ;
2024-12-19 21:03:38 +02:00
function removeGlobalShortcut ( namespace : string ) {
2025-01-09 18:07:02 +02:00
bindGlobalShortcut ( "" , null , namespace ) ;
2022-12-01 13:24:34 +01:00
}
2024-12-19 21:03:38 +02:00
function bindGlobalShortcut ( keyboardShortcut : string , handler : Handler | null , namespace : string | null = null ) {
2022-12-01 13:07:23 +01:00
bindElShortcut ( $ ( document ) , keyboardShortcut , handler , namespace ) ;
2022-12-01 00:17:15 +01:00
}
2025-03-16 18:31:31 +02:00
function bindElShortcut ( $el : JQuery < ElementType | Element > , keyboardShortcut : string , handler : Handler | null , namespace : string | null = null ) {
2022-12-01 00:17:15 +01:00
if ( utils . isDesktop ( ) ) {
keyboardShortcut = normalizeShortcut ( keyboardShortcut ) ;
2025-01-09 18:07:02 +02:00
let eventName = "keydown" ;
2022-12-01 00:17:15 +01:00
2022-12-01 10:03:04 +01:00
if ( namespace ) {
2022-12-21 15:19:05 +01:00
eventName += ` . ${ namespace } ` ;
2022-12-01 10:03:04 +01:00
2023-06-30 11:18:34 +02:00
// if there's a namespace, then we replace the existing event handler with the new one
2022-12-01 10:03:04 +01:00
$el . off ( eventName ) ;
}
// method can be called to remove the shortcut (e.g. when keyboardShortcut label is deleted)
if ( keyboardShortcut ) {
2025-01-09 18:07:02 +02:00
$el . bind ( eventName , keyboardShortcut , ( e ) = > {
2024-12-19 21:03:38 +02:00
if ( handler ) {
handler ( e ) ;
}
2022-12-01 10:03:04 +01:00
e . preventDefault ( ) ;
e . stopPropagation ( ) ;
} ) ;
}
2022-12-01 00:17:15 +01:00
}
}
/ * *
* Normalize to the form expected by the jquery . hotkeys . js
* /
2024-12-19 21:03:38 +02:00
function normalizeShortcut ( shortcut : string ) : string {
2022-12-01 10:03:04 +01:00
if ( ! shortcut ) {
return shortcut ;
}
2025-01-09 18:07:02 +02:00
return shortcut . toLowerCase ( ) . replace ( "enter" , "return" ) . replace ( "delete" , "del" ) . replace ( "ctrl+alt" , "alt+ctrl" ) . replace ( "meta+alt" , "alt+meta" ) ; // alt needs to be first;
2022-12-01 00:17:15 +01:00
}
export default {
bindGlobalShortcut ,
bindElShortcut ,
2022-12-01 13:24:34 +01:00
removeGlobalShortcut ,
2022-12-01 00:17:15 +01:00
normalizeShortcut
2025-01-09 18:07:02 +02:00
} ;