webhotkeys 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Easy solution to integrate keyboard hotkeys into the webpage.
4
4
 
5
5
  ```html
6
- <script src="https://cdn.jsdelivr.net/npm/webhotkeys@1.1.1/dist/WebHotkeys.min.js"
7
- integrity="sha384-GSvmX7qIMnxd5kgPsLoA3YzwUaZQcKBmCh66PVPZNibhc4VRxD+6h61FyJd3/gD9"
6
+ <script src="https://cdn.jsdelivr.net/npm/webhotkeys@2.0.0/dist/WebHotkeys.min.js"
7
+ integrity="sha384-df2GnKynN/JzZNyy6qYFcIWsAc3xYpa0ydIIxQXqESkSyazAjmZdRqMAwmXjxmQW"
8
8
  crossorigin="anonymous" data-register></script>
9
9
  ```
10
10
 
@@ -1,11 +1,11 @@
1
- /*! WebHotkeys v1.1.1 | LGPL-3.0-or-later | https://github.com/CZ-NIC/webhotkeys#readme
1
+ /*! WebHotkeys v2.0.0 | LGPL-3.0-or-later | https://github.com/CZ-NIC/webhotkeys#readme
2
2
  * Usage: <script src="WebHotkeys.min.js" data-register></script> then window.webHotkeys.grab("f", "Hint", fn)
3
3
  * Or without data-register: const wh = new window.WebHotkeys() */
4
- const WebHotkeysDefaults={replaceAccesskeys:!0,helpKey:"F1",help:"dialog",hintKey:"F2",attribute:"data-hotkey",groupAttribute:"data-hotkey-group",actionAttribute:"data-hotkey-action",observe:!0,onToggle:null,onTrigger:null,onMiss:null,hint:"title",ignore:null,sequenceTimeout:1e3,mac:null,warnConflicts:!1,inHidden:!1,remap:!0,onRemap:null},DEFAULT_STORAGE_KEY="webhotkeys.remap",FORM_TAGS=["INPUT","SELECT","TEXTAREA"],NON_TEXT_INPUT_TYPES=["checkbox","radio","submit","button","reset","image","file","range","color"],CONTROL_KEYS={range:["ArrowLeft","ArrowRight","Home","End"]},CLICKABLE_INPUT_TYPES=["checkbox","radio","submit","button","reset","image","file"],isTextInput=o=>FORM_TAGS.includes(o.tagName)&&!(o.tagName==="INPUT"&&NON_TEXT_INPUT_TYPES.includes(o.type)),defaultAction=o=>o.tagName==="DETAILS"?"toggle":o.tagName==="INPUT"&&CLICKABLE_INPUT_TYPES.includes(o.type)?"click":FORM_TAGS.includes(o.tagName)?"focus":"click",MODIFIER_KEYS=["Shift","Alt","Control","Meta"],MODIFIER_ALIASES={shift:"Shift",alt:"Alt",ctrl:"Control",control:"Control",meta:"Meta",cmd:"Meta",mod:"Mod"},KEY_ALIASES={return:"Enter",esc:"Escape",del:"Delete",ins:"Insert",space:"Space",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",pgup:"PageUp",pgdown:"PageDown",pgdn:"PageDown"},CODE_ALIASES={NumpadEnter:"Enter",NumpadDecimal:"Period",NumpadDivide:"Slash",NumpadSubtract:"Minus",NumpadAdd:"Equal",Numpad0:"Digit0",Numpad1:"Digit1",Numpad2:"Digit2",Numpad3:"Digit3",Numpad4:"Digit4",Numpad5:"Digit5",Numpad6:"Digit6",Numpad7:"Digit7",Numpad8:"Digit8",Numpad9:"Digit9"},MAC_SYMBOLS={ctrl:"⌃",alt:"⌥",shift:"⇧",meta:"⌘"};class Hotkey{constructor(e,t,i,s,n){this.action=e,this.hint=t,this.scope=i,this.sequence=Array.isArray(s)?s:[s],this.event=this.sequence[this.sequence.length-1],this.wh=n,this.allowInput=!1,this.allowHidden=null,this._displaced=null,this._base=null,this.defaultCombination=this.combination;const r=this.element=e instanceof HTMLElement?e:null;n._all.add(this),this.enabled=this._enable(),r&&(this.hint||(this.hint=r.title||r.innerText.substring(0,50)),this._hintElement())}_hintElement(e=null){const t=this.element,i=this.wh.options;if(!t||!i.hint)return;const s=this.clue;if(t.dataset.webhotkeysDisplayed===s)return;const n=` (${s})`,r=e?` (${e})`:null,l=a=>r&&a.includes(r)?a.replace(r,n):a+n;i.hint==="title"?t.title=l(t.title||""):i.hint==="text"&&(FORM_TAGS.includes(t.tagName)?t.labels?.[0]?.innerHTML&&(t.labels[0].innerHTML=l(t.labels[0].innerHTML)):t.innerHTML=l(t.innerHTML)),t.dataset.webhotkeysDisplayed=s}get clue(){return this.sequence.map(e=>Hotkey.comboText(e,this.wh?.isMac())).join(" ")}get combination(){return this.sequence.map(e=>Hotkey.comboText(e,!1)).join(" ")}get text(){return this.hint?`${this.clue}: ${this.hint}`:this.clue}static comboText(e,t=!1){const i=(e.key||e.code||"").replace(/^Digit(\d)$/,"$1");if(MODIFIER_KEYS.includes(i))return t?MAC_SYMBOLS[i==="Control"?"ctrl":i.toLowerCase()]:i;const s=["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]);if(t)return["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]).map(r=>MAC_SYMBOLS[r]).join("")+i;const n={ctrl:"Ctrl+",shift:"Shift+",alt:"Alt+",meta:"Meta+"};return["ctrl","shift","alt","meta"].filter(r=>s.includes(r)).map(r=>n[r]).join("")+i}static fromEvent(e){return MODIFIER_KEYS.includes(e.key)?e.key:Hotkey.comboText({...pickModifiers(e),[e.key?.length===1?"key":"code"]:e.key?.length===1?e.key:e.code})}get key_state(){return(this.event.key||this.event.code)+Hotkey.mod_state(this.event)}get registry(){return this.wh._hotkeys[this.key_state]||=[]}static mod_state(e,t=!1){return String((t?0:e.shiftKey<<3)|e.altKey<<2|e.ctrlKey<<1|e.metaKey)}static match(e,t){if(e.code&&e.code!==t.code&&CODE_ALIASES[t.code]!==e.code||e.key&&!keyEquals(e.key,t.key))return!1;const i=t.key?.length===1;return Hotkey.mod_state(e,i&&!/[A-Za-z]/.test(t.key))===Hotkey.mod_state(t,i&&!/[A-Za-z]/.test(t.key))}static isPrefixOf(e,t){return e.length<t.length&&e.every((i,s)=>Hotkey.match(i,t[s]))}rebind(e=null,t=!0){if(this._displaced=null,this._base=null,this._applySequence(this.wh._parseSequence(e||this.defaultCombination)),t){const i=this.combination;i===this.defaultCombination?delete this.wh._remap[this.defaultCombination]:this.wh._remap[this.defaultCombination]=i,this.wh._saveRemapping()}return this}_applySequence(e){const t=this.enabled,i=this.clue;return this.disable(),this.sequence=e,this.event=e[e.length-1],this._hintElement(i),t&&this.enable(),this}displace(e=null){if(e=e||null,this._displaced===e)return this;if(!e){const n=this._base;return this._displaced=null,this._base=null,n?this._applySequence(n):this}let t=MODIFIER_ALIASES[String(e).toLowerCase()];t==="Mod"&&(t=this.wh.isMac()?"Meta":"Control");const i={Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[t];if(!i)return console.warn(`WebHotkeys.js> displace: '${e}' is not a modifier`),this;const s=this._base||=this.sequence;return this._displaced=e,s[0][i]?this:this._applySequence([{...s[0],[i]:!0},...s.slice(1)])}_enable(){return this.registry.includes(this)||this.registry.unshift(this),this.enabled=!0}enable(){return this._enable(),this._notify(),this}disable(){const e=this.registry.indexOf(this);return e>-1&&this.registry.splice(e,1),this.enabled=!1,this._notify(),this}toggle(e=null){return e===null&&!this.enabled||e?this.enable():this.disable(),this}remove(){return this.disable(),this.wh._all.delete(this),this.element&&this.wh._dom.get(this.element)===this&&this.wh._dom.delete(this.element),Object.values(this.wh._groups).forEach(e=>{const t=e.indexOf(this);t>-1&&e.splice(t,1)}),this}_notify(){this.element&&this.wh.options.onToggle&&this.wh.options.onToggle.call(this,this.action,this.enabled)}}class HotkeyGroup extends Array{enable(){return this.toggle(!0)}disable(){return this.toggle(!1)}toggle(e=null){return this.forEach(t=>t.toggle(e)),this}displace(e=null){return this.forEach(t=>t.displace(e)),this}remove(){return this.slice().forEach(e=>e.remove()),this}}class WebHotkeys{constructor(e){e=this.options={...WebHotkeysDefaults,...e},this._hotkeys=Object.create(null),this._dom=new WeakMap,this._all=new Set,this._buffer=[],this._deferred=null,this._remap=Object.create(null),this._recording=null,this._lists=[],this._groups=Object.create(null);const t=s=>s.getAttribute?.(e.attribute)?.length,i=s=>!this._dom.has(s)&&this.grab(s.getAttribute(e.attribute),s.getAttribute("title"),s);return e.remap&&(this._storageKey=isString(e.remap)?e.remap:DEFAULT_STORAGE_KEY,this._loadRemapping()),e.replaceAccesskeys&&document.querySelectorAll("[accesskey]:not([accesskey=''])").forEach(s=>{s.setAttribute(e.attribute,"Alt+"+s.getAttribute("accesskey")),s.removeAttribute("accesskey")}),e.helpKey&&this.grab(e.helpKey,"Help",()=>this.toggleHelp()),e.hintKey&&this.grab(e.hintKey,"Show the hotkeys over the page",()=>this.toggleHints()),document.querySelectorAll(`[${e.attribute}]`).forEach(i),e.observe&&(this._observer=new MutationObserver(s=>{for(const n of s)if(n.type==="attributes"){const r=n.target;this._dom.get(r)?.disable()&&this._dom.delete(r),t(r)&&i(r)}else n.type==="childList"&&([...Array.from(n.addedNodes).filter(t),...Array.from(n.addedNodes).map(r=>Array.from(r.querySelectorAll?.(`[${e.attribute}]`)||[])).flat()].forEach(i),[...Array.from(n.removedNodes).filter(t),...Array.from(n.removedNodes).map(r=>Array.from(r.querySelectorAll?.(`[${e.attribute}]`)||[])).flat()].forEach(r=>this._dom.get(r).disable()&&this._dom.delete(r)))}),this._observer.observe(document,{attributeFilter:[e.attribute],childList:!0,subtree:!0})),this._listener=s=>this._trigger(s),document.addEventListener("keydown",this._listener,!0),this}setOptions(e){return this.options={...this.options,...e},this}destroy(){return document.removeEventListener("keydown",this._listener,!0),this._observer?.disconnect(),this._recording?.(),this._hideHelp(),this._hideHints(),this._lists.forEach(e=>e.destroy()),this._lists=[],Array.from(this._all).forEach(e=>e.remove()),this._hotkeys=Object.create(null),this._groups=Object.create(null),this._dom=new WeakMap,this._buffer=[],this._settleDeferred(!1),this._style?.remove?.(),this._style=this._sheet=void 0,this._destroyed=!0,this}isMac(){if(this.options.mac!==null&&this.options.mac!==void 0)return this.options.mac;const e=typeof navigator<"u"&&(navigator.userAgentData?.platform||navigator.platform||navigator.userAgent||"");return/mac|iphone|ipad|ipod/i.test(e||"")}activeElement(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e||null}getHotkeys(e=!0){return Array.from(this._all).filter(t=>!e||t.enabled)}getGroups(){const e=new Set(this.getHotkeys()),t=new Set,i=Object.entries(this._groups).map(([n,r])=>{const l=r.filter(a=>e.has(a));return l.forEach(a=>t.add(a)),{name:n,hotkeys:l}}).filter(n=>n.hotkeys.length),s=Array.from(e).filter(n=>!t.has(n));return[...s.length?[{name:"",hotkeys:s}]:[],...i]}getText(){return this.getGroups().map(({name:e,hotkeys:t})=>(e?`
4
+ const WebHotkeysDefaults={replaceAccesskeys:!0,helpKey:"F1",help:"dialog",hintKey:"F2",attribute:"data-hotkey",groupAttribute:"data-hotkey-group",actionAttribute:"data-hotkey-action",observe:!0,onToggle:null,onTrigger:null,onMiss:null,hint:"title",ignore:null,modal:"dialog:modal, [aria-modal=true]",sequenceTimeout:1e3,mac:null,warnConflicts:!1,inHidden:!1,remap:!0,onRemap:null},DEFAULT_STORAGE_KEY="webhotkeys.remap",FORM_TAGS=["INPUT","SELECT","TEXTAREA"],NON_TEXT_INPUT_TYPES=["checkbox","radio","submit","button","reset","image","file","range","color"],controlKeys=o=>{const e=o?.tagName==="INPUT"&&o.type;return e==="range"?["ArrowLeft","ArrowRight","Home","End"]:o?.tagName==="BUTTON"||o?.tagName==="SUMMARY"||["button","submit","reset"].includes(e)?["Enter"," "]:e==="checkbox"||e==="radio"?[" "]:o?.tagName==="A"&&o.href?["Enter"]:null},CLICKABLE_INPUT_TYPES=["checkbox","radio","submit","button","reset","image","file"],isTextInput=o=>FORM_TAGS.includes(o.tagName)&&!(o.tagName==="INPUT"&&NON_TEXT_INPUT_TYPES.includes(o.type)),defaultAction=o=>o.tagName==="DETAILS"?"toggle":o.tagName==="INPUT"&&CLICKABLE_INPUT_TYPES.includes(o.type)?"click":FORM_TAGS.includes(o.tagName)?"focus":"click",MODIFIER_KEYS=["Shift","Alt","Control","Meta"],MODIFIER_ALIASES={shift:"Shift",alt:"Alt",ctrl:"Control",control:"Control",meta:"Meta",cmd:"Meta",mod:"Mod"},KEY_ALIASES={return:"Enter",esc:"Escape",del:"Delete",ins:"Insert",space:"Space",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",pgup:"PageUp",pgdown:"PageDown",pgdn:"PageDown"},CODE_ALIASES={NumpadEnter:"Enter",NumpadDecimal:"Period",NumpadDivide:"Slash",NumpadSubtract:"Minus",NumpadAdd:"Equal",Numpad0:"Digit0",Numpad1:"Digit1",Numpad2:"Digit2",Numpad3:"Digit3",Numpad4:"Digit4",Numpad5:"Digit5",Numpad6:"Digit6",Numpad7:"Digit7",Numpad8:"Digit8",Numpad9:"Digit9"},MAC_SYMBOLS={ctrl:"⌃",alt:"⌥",shift:"⇧",meta:"⌘"};class Hotkey{constructor(e,t,i,s,n){this.action=e,this.hint=t,this.scope=i,this.sequence=Array.isArray(s)?s:[s],this.event=this.sequence[this.sequence.length-1],this.wh=n,this.allowInput=!1,this.allowHidden=null,this._displaced=null,this._base=null,this.defaultCombination=this.combination;const r=this.element=e instanceof HTMLElement?e:null;n._all.add(this),this.enabled=this._enable(),r&&(this.hint||(this.hint=r.title||r.innerText.substring(0,50)),this._hintElement())}_hintElement(e=null){const t=this.element,i=this.wh.options;if(!t||!i.hint)return;const s=this.clue;if(t.dataset.webhotkeysDisplayed===s)return;const n=` (${s})`,r=e?` (${e})`:null,l=h=>r&&h.includes(r)?h.replace(r,n):h+n;i.hint==="title"?t.title=l(t.title||""):i.hint==="text"&&(FORM_TAGS.includes(t.tagName)?t.labels?.[0]?.innerHTML&&(t.labels[0].innerHTML=l(t.labels[0].innerHTML)):t.innerHTML=l(t.innerHTML)),t.dataset.webhotkeysDisplayed=s}get clue(){return this.sequence.map(e=>Hotkey.comboText(e,this.wh?.isMac())).join(" ")}get combination(){return this.sequence.map(e=>Hotkey.comboText(e,!1)).join(" ")}get text(){return this.hint?`${this.clue}: ${this.hint}`:this.clue}static comboText(e,t=!1){const i=(e.key||e.code||"").replace(/^Digit(\d)$/,"$1");if(MODIFIER_KEYS.includes(i))return t?MAC_SYMBOLS[i==="Control"?"ctrl":i.toLowerCase()]:i;const s=["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]);if(t)return["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]).map(r=>MAC_SYMBOLS[r]).join("")+i;const n={ctrl:"Ctrl+",shift:"Shift+",alt:"Alt+",meta:"Meta+"};return["ctrl","shift","alt","meta"].filter(r=>s.includes(r)).map(r=>n[r]).join("")+i}static fromEvent(e){return MODIFIER_KEYS.includes(e.key)?e.key:Hotkey.comboText({...pickModifiers(e),[e.key?.length===1?"key":"code"]:e.key?.length===1?e.key:e.code})}get key_state(){return(this.event.key||this.event.code)+Hotkey.mod_state(this.event)}get registry(){return this.wh._hotkeys[this.key_state]||=[]}static mod_state(e,t=!1){return String((t?0:e.shiftKey<<3)|e.altKey<<2|e.ctrlKey<<1|e.metaKey)}static match(e,t){if(e.code&&e.code!==t.code&&CODE_ALIASES[t.code]!==e.code||e.key&&!keyEquals(e.key,t.key))return!1;const i=t.key?.length===1;return Hotkey.mod_state(e,i&&!/[A-Za-z]/.test(t.key))===Hotkey.mod_state(t,i&&!/[A-Za-z]/.test(t.key))}static isPrefixOf(e,t){return e.length<t.length&&e.every((i,s)=>Hotkey.match(i,t[s]))}rebind(e=null,t=!0){if(this._displaced=null,this._base=null,this._applySequence(this.wh._parseSequence(e||this.defaultCombination)),t){const i=this.combination;i===this.defaultCombination?delete this.wh._remap[this.defaultCombination]:this.wh._remap[this.defaultCombination]=i,this.wh._saveRemapping()}return this}_applySequence(e){const t=this.enabled,i=this.clue;return this.disable(),this.sequence=e,this.event=e[e.length-1],this._hintElement(i),t&&this.enable(),this}displace(e=null){if(e=e||null,this._displaced===e)return this;if(!e){const n=this._base;return this._displaced=null,this._base=null,n?this._applySequence(n):this}let t=MODIFIER_ALIASES[String(e).toLowerCase()];t==="Mod"&&(t=this.wh.isMac()?"Meta":"Control");const i={Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[t];if(!i)return console.warn(`WebHotkeys.js> displace: '${e}' is not a modifier`),this;const s=this._base||=this.sequence;return this._displaced=e,s[0][i]?this:this._applySequence([{...s[0],[i]:!0},...s.slice(1)])}_enable(){return this.registry.includes(this)||this.registry.unshift(this),this.enabled=!0}enable(){return this._enable(),this._notify(),this}disable(){const e=this.registry.indexOf(this);return e>-1&&this.registry.splice(e,1),this.enabled=!1,this._notify(),this}toggle(e=null){return e===null&&!this.enabled||e?this.enable():this.disable(),this}remove(){return this.disable(),this.wh._all.delete(this),this.element&&this.wh._dom.get(this.element)===this&&this.wh._dom.delete(this.element),Object.values(this.wh._groups).forEach(e=>{const t=e.indexOf(this);t>-1&&e.splice(t,1)}),this}_notify(){this.element&&this.wh.options.onToggle&&this.wh.options.onToggle.call(this,this.action,this.enabled)}}class HotkeyGroup extends Array{enable(){return this.toggle(!0)}disable(){return this.toggle(!1)}toggle(e=null){return this.forEach(t=>t.toggle(e)),this}displace(e=null){return this.forEach(t=>t.displace(e)),this}remove(){return this.slice().forEach(e=>e.remove()),this}}class WebHotkeys{constructor(e){e=this.options={...WebHotkeysDefaults,...e},this._hotkeys=Object.create(null),this._dom=new WeakMap,this._all=new Set,this._buffer=[],this._deferred=null,this._remap=Object.create(null),this._recording=null,this._lists=[],this._suspensions=[],this._yielded=null,this._groups=Object.create(null);const t=s=>s.getAttribute?.(e.attribute)?.length,i=s=>!this._dom.has(s)&&this.grab(s.getAttribute(e.attribute),s.getAttribute("title"),s);return e.remap&&(this._storageKey=isString(e.remap)?e.remap:DEFAULT_STORAGE_KEY,this._loadRemapping()),e.replaceAccesskeys&&document.querySelectorAll("[accesskey]:not([accesskey=''])").forEach(s=>{s.setAttribute(e.attribute,"Alt+"+s.getAttribute("accesskey")),s.removeAttribute("accesskey")}),e.helpKey&&this.grab(e.helpKey,"Help",()=>this.toggleHelp()),e.hintKey&&this.grab(e.hintKey,"Show the hotkeys over the page",()=>this.toggleHints()),document.querySelectorAll(`[${e.attribute}]`).forEach(i),e.observe&&(this._observer=new MutationObserver(s=>{for(const n of s)if(n.type==="attributes"){const r=n.target;this._dom.get(r)?.disable()&&this._dom.delete(r),t(r)&&i(r)}else n.type==="childList"&&([...Array.from(n.addedNodes).filter(t),...Array.from(n.addedNodes).map(r=>Array.from(r.querySelectorAll?.(`[${e.attribute}]`)||[])).flat()].forEach(i),[...Array.from(n.removedNodes).filter(t),...Array.from(n.removedNodes).map(r=>Array.from(r.querySelectorAll?.(`[${e.attribute}]`)||[])).flat()].forEach(r=>this._dom.get(r).disable()&&this._dom.delete(r)))}),this._observer.observe(document,{attributeFilter:[e.attribute],childList:!0,subtree:!0})),this._listener=s=>this._trigger(s),document.addEventListener("keydown",this._listener,!0),this._fallbackListener=s=>this._fallback(s),typeof window<"u"&&window.addEventListener?.("keydown",this._fallbackListener),this}setOptions(e){return this.options={...this.options,...e},this}destroy(){return document.removeEventListener("keydown",this._listener,!0),typeof window<"u"&&window.removeEventListener?.("keydown",this._fallbackListener),this._observer?.disconnect(),this._recording?.(),this._hideHelp(),this._hideHints(),this._lists.forEach(e=>e.destroy()),this._lists=[],Array.from(this._all).forEach(e=>e.remove()),this._hotkeys=Object.create(null),this._groups=Object.create(null),this._dom=new WeakMap,this._buffer=[],this._suspensions=[],this._yielded=null,this._settleDeferred(!1),this._style?.remove?.(),this._style=this._sheet=void 0,this._destroyed=!0,this}isMac(){if(this.options.mac!==null&&this.options.mac!==void 0)return this.options.mac;const e=typeof navigator<"u"&&(navigator.userAgentData?.platform||navigator.platform||navigator.userAgent||"");return/mac|iphone|ipad|ipod/i.test(e||"")}activeElement(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e||null}suspend(e=null){const t=e?Array.isArray(e)&&!(e instanceof HotkeyGroup)?e:[e]:[];return this._suspensions.push(t),()=>{const i=this._suspensions.indexOf(t);i>-1&&this._suspensions.splice(i,1)}}get suspended(){return this._suspensions.length>0}_modal(){const{modal:e}=this.options;if(!e||typeof document>"u")return null;try{return Array.from(document.querySelectorAll(e)).filter(isVisible).pop()||null}catch{return null}}_admits(e,t,i){if(!this._suspensions.every(r=>r.some(l=>l===e||(isString(l)?this._groups[l]:l)?.includes?.(e))))return!1;if(!i)return!0;const{element:s,scope:n}=e;if(s)return i.contains(s);if(!n)return!1;if(isString(n)){const r=t?.closest?.(n);return!!r&&i.contains(r)}return i.contains(typeof n=="function"?t:n)}getHotkeys(e=!0){return Array.from(this._all).filter(t=>!e||t.enabled)}getGroups(){const e=new Set(this.getHotkeys()),t=new Set,i=Object.entries(this._groups).map(([n,r])=>{const l=r.filter(h=>e.has(h));return l.forEach(h=>t.add(h)),{name:n,hotkeys:l}}).filter(n=>n.hotkeys.length),s=Array.from(e).filter(n=>!t.has(n));return[...s.length?[{name:"",hotkeys:s}]:[],...i]}getText(){return this.getGroups().map(({name:e,hotkeys:t})=>(e?`
5
5
  **${e}**
6
6
  `:"")+t.map(i=>i.text).join(`
7
7
  `)).join(`
8
- `).trim()}getConflicts(){const e=new Map;return this.getHotkeys().filter(t=>!t.scope).forEach(t=>{const i=t.combination;e.set(i,[...e.get(i)||[],t])}),Array.from(e).filter(([,t])=>t.length>1).map(([t,i])=>({combination:t,hotkeys:i}))}grab(e,t,i,s=null){let n=!1,r=null,l=null;s&&typeof s=="object"&&Object.getPrototypeOf(Object.getPrototypeOf(s)??{})===null&&(n=s.inInput??!1,r=s.inHidden??null,l=s.group??null,s=s.scope??null);let a=!e||!i;if(isString(i))try{i=document.querySelector(i)}catch{a=!0}if(a){console.error(`WebHotkeys.js> Unknown action hotkey for action ${e} ${i}`);return}const h=new Hotkey(i,t,s,this._parseSequence(e),this);h.allowInput=n,h.allowHidden=r;const c=this._remap[h.defaultCombination];c&&c!==h.combination&&h.rebind(c,!1);const{element:f}=h,{groupAttribute:y}=this.options;if(f){this._dom.set(f,h);const p=f.closest(`[${y}]`)?.getAttribute(y);p&&this.group(p).push(h)}if(l&&this.group(l).push(h),this.options.warnConflicts){const p=h.combination,g=h.registry.filter(u=>!u.scope&&u.combination===p);if(g.length>1&&console.warn(`WebHotkeys.js> ${p} is grabbed ${g.length}x:`,g.map(u=>u.hint||u.action)),!h.scope){const u=this.getHotkeys().find(d=>d!==h&&!d.scope&&(Hotkey.isPrefixOf(d.sequence,h.sequence)||Hotkey.isPrefixOf(h.sequence,d.sequence)));if(u){const[d,m]=h.sequence.length<u.sequence.length?[h,u]:[u,h];console.warn(`WebHotkeys.js> ${d.combination} shadows the sequence ${m.combination} - the plain hotkey fires only after a ${this.options.sequenceTimeout}ms delay, in case the sequence doesn't complete:`,[d.hint||d.action,m.hint||m.action])}}}return h}group(e,t=null){const i=this._groups[e]||=new HotkeyGroup;return t&&i.push(...t.map(s=>this.grab(...s)).filter(s=>!i.includes(s))),i}_parseSequence(e){return String(e).split(" ").filter(t=>t.length).map(t=>this._parseHotkey(t))}_parseHotkey(e){const t=e.split("+");t[t.length-1]===""&&t[t.length-2]===""&&t.splice(t.length-2,2,"+");let i=t.pop();i=KEY_ALIASES[i.toLowerCase()]||i;const s={},n=l=>{const a=MODIFIER_ALIASES[l.toLowerCase()];return a==="Mod"?this.isMac()?"Meta":"Control":a},r=t.length===0&&n(i);return r?(s.key=r,s[{Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[r]]=!0):s[i.length===1?"key":"code"]=i,t.forEach(l=>{const a=n(l);a?s[{Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[a]]=!0:console.warn(`Unknown modifier at ${e}`)}),s}record(e,{sequence:t=!1,onProgress:i=null}={}){const s=[];let n=null,r=null;const l=c=>{if(!MODIFIER_KEYS.includes(c.key)){if(c.preventDefault?.(),c.stopPropagation?.(),s.push(Hotkey.fromEvent(c)),r=c,!t||typeof setTimeout!="function")return a();clearTimeout(n),n=setTimeout(a,this.options.sequenceTimeout),i?.call(this,s.join(" "),c)}},a=()=>{h(),e.call(this,s.join(" "),r)},h=()=>{n&&(clearTimeout(n),n=null),document.removeEventListener("keydown",l,!0),this._recording=null};return this._recording?.(),this._recording=h,document.addEventListener("keydown",l,!0),h}remapping(e){return arguments.length===0?{...this._remap}:(this._applyRemapping(e,!0),this)}_applyRemapping(e,t){this._remap=Object.create(null);const i=[];Object.entries(e||{}).forEach(([s,n])=>{isSafeCombination(s)&&isSafeCombination(n)?this._remap[s]=n:i.push(`${s} -> ${n}`)}),i.length&&console.warn("WebHotkeys.js> Dropping a remapping that is not a key combination:",i),this.getHotkeys(!1).forEach(s=>{const n=this._remap[s.defaultCombination]||s.defaultCombination;n!==s.combination&&s.rebind(n,!1)}),t&&this._saveRemapping()}_loadRemapping(){if(typeof localStorage>"u")return this;let e;try{e=localStorage.getItem(this._storageKey)}catch(i){return console.warn("WebHotkeys.js> Cannot read the stored remapping",i),this._storageKey=null,this}if(!e)return this;const t=parseRemapping(e);return t?(this._applyRemapping(t,!1),this):(console.warn(`WebHotkeys.js> localStorage['${this._storageKey}'] holds a foreign value. The remapping will not be stored; point the \`remap\` option to another key.`),this._storageKey=null,this)}_saveRemapping(){if(this.options.onRemap?.call(this,this.remapping()),this._storageKey&&typeof localStorage<"u")try{localStorage.setItem(this._storageKey,JSON.stringify(this.remapping()))}catch(e){console.warn("WebHotkeys.js> Cannot store the remapping",e)}}list(e,t={}){const i=new _List(this);return i._configure(e,t),this._lists.push(i),i}grid(e,t,i={}){return new _Grid(this,e,t,i)}_isTextContext(e,t){const i=t?.tagName==="INPUT"&&CONTROL_KEYS[t.type];return i?!e.altKey&&!e.metaKey&&!e.ctrlKey&&i.includes(e.key):!e.altKey&&!e.metaKey&&(e.key?.length===1||["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","Delete","Backspace"].includes(e.key)||["Tab","Enter"].includes(e.key)&&!e.ctrlKey)&&!!t&&(isTextInput(t)||t.contentEditable==="true")}_candidates(e){const t=[];if(e.code&&t.push(e.code+Hotkey.mod_state(e)),e.key){const i=e.key.length===1;t.push((i&&/[A-Z]/.test(e.key)?e.key.toLowerCase():e.key)+Hotkey.mod_state(e,i&&!/[A-Za-z]/.test(e.key)))}return CODE_ALIASES[e.code]&&t.push(CODE_ALIASES[e.code]+Hotkey.mod_state(e)),t.flatMap(i=>this._hotkeys[i]?.filter(s=>s.enabled)||[]).sort((i,s)=>s.sequence.length-i.sequence.length)}_matchesSequence(e,t){const i=e.sequence.slice(0,-1);let s=this._buffer.length-1;for(let n=i.length-1;n>=0;n--){const r=i[n];for(;s>=0&&!MODIFIER_KEYS.includes(r.key)&&MODIFIER_KEYS.includes(this._buffer[s].event.key);)s--;const l=this._buffer[s--];if(!l||t-l.time>this.options.sequenceTimeout||!Hotkey.match(r,l.event))return!1}return!0}_pendingSequence(e){return this.getHotkeys().some(t=>t.sequence.length>this._buffer.length&&this._buffer.every((i,s)=>e-i.time<=this.options.sequenceTimeout&&Hotkey.match(t.sequence[s],i.event)))}_matchesPrefix(e,t){return this.getHotkeys().some(i=>i.sequence.length>this._buffer.length+1&&this._buffer.every((s,n)=>t-s.time<=this.options.sequenceTimeout&&Hotkey.match(i.sequence[n],s.event))&&Hotkey.match(i.sequence[this._buffer.length],e))}_deferPlainHotkey(e,t){this._deferred={hotkey:e,event:t,timer:setTimeout(()=>this._settleDeferred(!0),this.options.sequenceTimeout)}}_settleDeferred(e){const t=this._deferred;t&&(clearTimeout(t.timer),this._deferred=null,e&&this._fireHotkey(t.hotkey,t.event))}_fireHotkey(e,t){const{action:i,element:s,scope:n}=e,r=this.activeElement();if(n&&!(isString(n)?r?.closest?.(n):n instanceof Function?n.call(this,r,t):n.contains?.(r)))return!1;let l;if(s){if(s.disabled||!isVisible(s)&&!(e.allowHidden??this.options.inHidden))return!1;this._act(s)}else l=i.call(this,t);return l===!1?!1:(this._buffer.length=0,this.options.onTrigger?.call(this,e,t),t.stopPropagation?.(),t.preventDefault?.(),!0)}_trigger(e){if(this._destroyed||this._recording)return;if(this._help?.open){["Escape","F1"].some(r=>e.key===r||e.code===r)&&(this._hideHelp(),e.preventDefault?.(),e.stopPropagation?.());return}this._hideHints();const t=this.activeElement(),{ignore:i}=this.options;if(i&&t&&(isString(i)?t.closest?.(i):i.call(this,t,e)))return;const s=this._isTextContext(e,t),n=Date.now();for(const r of this._candidates(e))if(!(s&&!r.allowInput)&&!(r.sequence.length>1&&!this._matchesSequence(r,n))){if(r.sequence.length===1&&this._matchesPrefix(e,n)){this._deferPlainHotkey(r,e);continue}if(this._fireHotkey(r,e))return this._settleDeferred(!1),!0}if(!s){for(this._buffer.push({event:e,time:n});this._buffer.length&&(this._buffer.length>8||n-this._buffer[0].time>this.options.sequenceTimeout);)this._buffer.shift();if(this._pendingSequence(n)){e.preventDefault?.(),e.stopPropagation?.();return}this._buffer.length=0,this._settleDeferred(!0),this.options.onMiss?.call(this,e)}}_act(e){switch(e.getAttribute?.(this.options.actionAttribute)||defaultAction(e)){case"focus":return e.focus();case"none":return;case"toggle":e.tagName==="DETAILS"?e.open=!e.open:e.type==="checkbox"?(e.checked=!e.checked,e.dispatchEvent?.(new Event("change",{bubbles:!0}))):this._activate(e);return;default:return this._activate(e)}}_activate(e){e.click(),e.type==="radio"&&e.focus?.()}simulate(e){return e.constructor===String?this._parseSequence(e).map(t=>this._trigger(completeSimulatedEvent(t))).pop():this._trigger(completeSimulatedEvent(e))}toggleHelp(e=null){return e??!this._help?.open?this._showHelp():this._hideHelp()}_showHelp(){const e=this.options.help==="dialog"&&createEl("dialog");if(!e?.showModal)return typeof alert=="function"?alert(this.getText()):console.log(this.getText()),this;this._hideHelp(),this._injectStyle(),e.className="webhotkeys-dialog";const t=createEl("div","webhotkeys-head",e);createEl("strong","",t).textContent="Keyboard shortcuts";const i=createEl("input","webhotkeys-filter",t);i.type="search",i.placeholder="Filter…";const s=createEl("button","webhotkeys-close",t);s.textContent="✕",s.onclick=()=>this._hideHelp();const n=createEl("div","webhotkeys-body",e);return this.getGroups().forEach(({name:r,hotkeys:l})=>{r&&(createEl("h3","",n).textContent=r),l.forEach(a=>{const h=createEl("div","webhotkeys-row",n),c=createEl(this.options.remap?"button":"kbd","webhotkeys-key",h);c.textContent=a.clue,createEl("span","webhotkeys-hint",h).textContent=a.hint,this.options.remap&&this._makeEditable(h,c,a)})}),this.options.remap&&(createEl("p","webhotkeys-note",n).textContent="Click a combination to remap it."),i.oninput=()=>{const r=i.value.toLowerCase();n.querySelectorAll(".webhotkeys-row").forEach(l=>{l.style.display=l.textContent.toLowerCase().includes(r)?"":"none"})},document.body.appendChild(e),this._help=e,e.addEventListener("close",()=>this._hideHelp()),e.addEventListener("cancel",r=>this._recording&&r.preventDefault?.()),e.showModal(),this}_makeEditable(e,t,i){const s="Click and press your own combination";t.type="button";const n=createEl("button","webhotkeys-reset",e);n.textContent="↺",n.title="Back to the default combination";const r=(l=!1)=>{t.textContent=i.clue,t.className="webhotkeys-key";const a=i.combination!==i.defaultCombination;n.style.display=a?"":"none";const h=this.getConflicts().find(c=>c.combination===i.combination);e.className="webhotkeys-row"+(h?" webhotkeys-clash":""),t.title=h?`Also used by: ${h.hotkeys.filter(c=>c!==i).map(c=>c.hint).join(", ")}`:s,l&&t.focus?.()};r(),n.onclick=()=>{i.rebind(),r(!0)},t.onclick=()=>{if(this._recording)return this._recording();t.className="webhotkeys-key webhotkeys-recording",t.textContent="…",this.record(l=>{l!=="Escape"&&i.rebind(l),r(!0)},{sequence:!0,onProgress:l=>{if(l.split(" ").pop()==="Escape")return this._recording?.(),r(!0);t.textContent=l+" …"}})}}_hideHelp(){if(this._recording?.(),this._help){const e=this._help;this._help=null,e.close?.(),e.remove?.()}return this}_showHints(){if(typeof document>"u"||!document.body)return this;this._hideHints(),this._injectStyle();const e=createEl("div","webhotkeys-hints");return this.getHotkeys().forEach(t=>{const i=t.element;if(!i||!isVisible(i))return;const s=i.getBoundingClientRect?.();if(!s||!s.width&&!s.height)return;const n=createEl("kbd","webhotkeys-badge",e);n.textContent=t.clue,n.style.left=`${s.left+window.scrollX}px`,n.style.top=`${s.top+window.scrollY}px`}),document.body.appendChild(e),this._hints=e,this._dismissHints=()=>this._hideHints(),window.addEventListener("scroll",this._dismissHints,{passive:!0,once:!0}),window.addEventListener("resize",this._dismissHints,{once:!0}),this}_hideHints(){return this._hints&&(this._hints.remove?.(),this._hints=null,window.removeEventListener("scroll",this._dismissHints),window.removeEventListener("resize",this._dismissHints)),this}toggleHints(e=null){return e??!this._hints?this._showHints():this._hideHints()}_injectStyle(){this._style||typeof document>"u"||!document.head||(this._style=createEl("style"),this._style.textContent=`
8
+ `).trim()}getConflicts(){const e=new Map;return this.getHotkeys().filter(t=>!t.scope).forEach(t=>{const i=t.combination;e.set(i,[...e.get(i)||[],t])}),Array.from(e).filter(([,t])=>t.length>1).map(([t,i])=>({combination:t,hotkeys:i}))}grab(e,t,i,s=null){let n=!1,r=null,l=null;s&&typeof s=="object"&&Object.getPrototypeOf(Object.getPrototypeOf(s)??{})===null&&(n=s.inInput??!1,r=s.inHidden??null,l=s.group??null,s=s.scope??null);let h=!e||!i;if(isString(i))try{i=document.querySelector(i)}catch{h=!0}if(h){console.error(`WebHotkeys.js> Unknown action hotkey for action ${e} ${i}`);return}const a=new Hotkey(i,t,s,this._parseSequence(e),this);a.allowInput=n,a.allowHidden=r;const c=this._remap[a.defaultCombination];c&&c!==a.combination&&a.rebind(c,!1);const{element:f}=a,{groupAttribute:y}=this.options;if(f){this._dom.set(f,a);const p=f.closest(`[${y}]`)?.getAttribute(y);p&&this.group(p).push(a)}if(l&&this.group(l).push(a),this.options.warnConflicts){const p=a.combination,g=a.registry.filter(u=>!u.scope&&u.combination===p);if(g.length>1&&console.warn(`WebHotkeys.js> ${p} is grabbed ${g.length}x:`,g.map(u=>u.hint||u.action)),!a.scope){const u=this.getHotkeys().find(d=>d!==a&&!d.scope&&(Hotkey.isPrefixOf(d.sequence,a.sequence)||Hotkey.isPrefixOf(a.sequence,d.sequence)));if(u){const[d,m]=a.sequence.length<u.sequence.length?[a,u]:[u,a];console.warn(`WebHotkeys.js> ${d.combination} shadows the sequence ${m.combination} - the plain hotkey fires only after a ${this.options.sequenceTimeout}ms delay, in case the sequence doesn't complete:`,[d.hint||d.action,m.hint||m.action])}}}return a}group(e,t=null){const i=this._groups[e]||=new HotkeyGroup;return t&&i.push(...t.map(s=>this.grab(...s)).filter(s=>!i.includes(s))),i}_parseSequence(e){return String(e).split(" ").filter(t=>t.length).map(t=>this._parseHotkey(t))}_parseHotkey(e){const t=e.split("+");t[t.length-1]===""&&t[t.length-2]===""&&t.splice(t.length-2,2,"+");let i=t.pop();i=KEY_ALIASES[i.toLowerCase()]||i;const s={},n=l=>{const h=MODIFIER_ALIASES[l.toLowerCase()];return h==="Mod"?this.isMac()?"Meta":"Control":h},r=t.length===0&&n(i);return r?(s.key=r,s[{Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[r]]=!0):s[i.length===1?"key":"code"]=i,t.forEach(l=>{const h=n(l);h?s[{Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"}[h]]=!0:console.warn(`Unknown modifier at ${e}`)}),s}record(e,{sequence:t=!1,onProgress:i=null}={}){const s=[];let n=null,r=null;const l=c=>{if(!MODIFIER_KEYS.includes(c.key)){if(c.preventDefault?.(),c.stopPropagation?.(),s.push(Hotkey.fromEvent(c)),r=c,!t||typeof setTimeout!="function")return h();clearTimeout(n),n=setTimeout(h,this.options.sequenceTimeout),i?.call(this,s.join(" "),c)}},h=()=>{a(),e.call(this,s.join(" "),r)},a=()=>{n&&(clearTimeout(n),n=null),document.removeEventListener("keydown",l,!0),this._recording=null};return this._recording?.(),this._recording=a,document.addEventListener("keydown",l,!0),a}remapping(e){return arguments.length===0?{...this._remap}:(this._applyRemapping(e,!0),this)}_applyRemapping(e,t){this._remap=Object.create(null);const i=[];Object.entries(e||{}).forEach(([s,n])=>{isSafeCombination(s)&&isSafeCombination(n)?this._remap[s]=n:i.push(`${s} -> ${n}`)}),i.length&&console.warn("WebHotkeys.js> Dropping a remapping that is not a key combination:",i),this.getHotkeys(!1).forEach(s=>{const n=this._remap[s.defaultCombination]||s.defaultCombination;n!==s.combination&&s.rebind(n,!1)}),t&&this._saveRemapping()}_loadRemapping(){if(typeof localStorage>"u")return this;let e;try{e=localStorage.getItem(this._storageKey)}catch(i){return console.warn("WebHotkeys.js> Cannot read the stored remapping",i),this._storageKey=null,this}if(!e)return this;const t=parseRemapping(e);return t?(this._applyRemapping(t,!1),this):(console.warn(`WebHotkeys.js> localStorage['${this._storageKey}'] holds a foreign value. The remapping will not be stored; point the \`remap\` option to another key.`),this._storageKey=null,this)}_saveRemapping(){if(this.options.onRemap?.call(this,this.remapping()),this._storageKey&&typeof localStorage<"u")try{localStorage.setItem(this._storageKey,JSON.stringify(this.remapping()))}catch(e){console.warn("WebHotkeys.js> Cannot store the remapping",e)}}list(e,t={}){const i=new _List(this);return i._configure(e,t),this._lists.push(i),i}grid(e,t,i={}){return new _Grid(this,e,t,i)}_isTextContext(e,t){return!e.altKey&&!e.metaKey&&!e.ctrlKey&&controlKeys(t)?.includes(e.key)?!0:!e.altKey&&!e.metaKey&&(e.key?.length===1||["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","Delete","Backspace"].includes(e.key)||["Tab","Enter","Escape"].includes(e.key)&&!e.ctrlKey)&&!!t&&isEditable(t)}_candidates(e){const t=[];if(e.code&&t.push(e.code+Hotkey.mod_state(e)),e.key){const s=e.key.length===1;t.push((s&&/[A-Z]/.test(e.key)?e.key.toLowerCase():e.key)+Hotkey.mod_state(e,s&&!/[A-Za-z]/.test(e.key)))}t[0]===t[1]&&t.pop();const i=t.length;return CODE_ALIASES[e.code]&&t.push(CODE_ALIASES[e.code]+Hotkey.mod_state(e)),t.flatMap((s,n)=>(this._hotkeys[s]||[]).filter(r=>r.enabled).map(r=>({hotkey:r,alias:n>=i}))).sort((s,n)=>n.hotkey.sequence.length-s.hotkey.sequence.length||s.alias-n.alias||!!n.hotkey.scope-!!s.hotkey.scope).map(({hotkey:s})=>s)}_matchesSequence(e,t){const i=e.sequence.slice(0,-1);let s=this._buffer.length-1;for(let n=i.length-1;n>=0;n--){const r=i[n];for(;s>=0&&!MODIFIER_KEYS.includes(r.key)&&MODIFIER_KEYS.includes(this._buffer[s].event.key);)s--;const l=this._buffer[s--];if(!l||t-l.time>this.options.sequenceTimeout||!Hotkey.match(r,l.event))return!1}return!0}_pendingSequence(e,t){return this.getHotkeys().some(i=>t(i)&&i.sequence.length>this._buffer.length&&this._buffer.every((s,n)=>e-s.time<=this.options.sequenceTimeout&&Hotkey.match(i.sequence[n],s.event)))}_matchesPrefix(e,t,i){return this.getHotkeys().some(s=>i(s)&&s.sequence.length>this._buffer.length+1&&this._buffer.every((n,r)=>t-n.time<=this.options.sequenceTimeout&&Hotkey.match(s.sequence[r],n.event))&&Hotkey.match(s.sequence[this._buffer.length],e))}_deferPlainHotkey(e,t){this._deferred={hotkey:e,event:t,timer:setTimeout(()=>this._settleDeferred(!0),this.options.sequenceTimeout)}}_settleDeferred(e){const t=this._deferred;t&&(clearTimeout(t.timer),this._deferred=null,e&&this._fireHotkey(t.hotkey,t.event))}_fireHotkey(e,t,i=this._modal()){const{action:s,element:n,scope:r}=e,l=this.activeElement();if(!this._admits(e,l,i)||r&&!(isString(r)?l?.closest?.(r):typeof r=="function"?r.call(this,l,t):r.contains?.(l)))return!1;let h;if(n){if(n.disabled||!isVisible(n)&&!(e.allowHidden??this.options.inHidden))return!1;this._act(n)}else h=s.call(this,t);return h===!1?!1:(this._buffer.length=0,this.options.onTrigger?.call(this,e,t),t.stopPropagation?.(),t.preventDefault?.(),!0)}_trigger(e){if(this._destroyed||(this._yielded=null,this._recording))return;if(this._help?.open){["Escape","F1"].some(r=>e.key===r||e.code===r)&&(this._hideHelp(),e.preventDefault?.(),e.stopPropagation?.());return}this._hideHints();const t=this.activeElement(),{ignore:i}=this.options;if(i&&t&&(isString(i)?t.closest?.(i):i.call(this,t,e)))return;const s=this._isTextContext(e,t),n=this._dispatch(e,t,s?"typing":"normal");return s&&!n&&e.key==="Escape"&&(this._yielded={event:e,field:t}),n}_fallback(e){const t=this._yielded;if(!t||t.event!==e||(this._yielded=null,this._destroyed||e.defaultPrevented))return;const{field:i}=t;if(!(i.tagName==="INPUT"&&i.type==="search"&&i.value))return this._dispatch(e,this.activeElement(),"fallback")}_dispatch(e,t,i){const s=i==="typing",n=Date.now(),r=this._modal(),l=h=>this._admits(h,t,r);for(const h of this._candidates(e))if(!(s?!h.allowInput:i==="fallback"&&h.allowInput)&&!(h.sequence.length>1&&!this._matchesSequence(h,n))){if(h.sequence.length===1&&l(h)&&this._matchesPrefix(e,n,l)){this._deferPlainHotkey(h,e);continue}if(this._fireHotkey(h,e,r))return this._settleDeferred(!1),!0}if(!s){for(this._buffer.push({event:e,time:n});this._buffer.length&&(this._buffer.length>8||n-this._buffer[0].time>this.options.sequenceTimeout);)this._buffer.shift();if(this._pendingSequence(n,l)){e.preventDefault?.(),e.stopPropagation?.();return}this._buffer.length=0,this._settleDeferred(!0),this.options.onMiss?.call(this,e)}}_act(e){switch(e.getAttribute?.(this.options.actionAttribute)||defaultAction(e)){case"focus":return e.focus();case"none":return;case"toggle":e.tagName==="DETAILS"?e.open=!e.open:e.type==="checkbox"?(e.checked=!e.checked,e.dispatchEvent?.(new Event("change",{bubbles:!0}))):this._activate(e);return;default:return this._activate(e)}}_activate(e){e.click(),e.type==="radio"&&e.focus?.()}simulate(e){const t=i=>{i=completeSimulatedEvent(i);const s=this._trigger(i);return this._yielded?.event===i?this._fallback(i):s};return e.constructor===String?this._parseSequence(e).map(t).pop():t(e)}toggleHelp(e=null){return e??!this._help?.open?this._showHelp():this._hideHelp()}_showHelp(){const e=this.options.help==="dialog"&&createEl("dialog");if(!e?.showModal)return typeof alert=="function"?alert(this.getText()):console.log(this.getText()),this;this._hideHelp(),this._injectStyle(),e.className="webhotkeys-dialog";const t=createEl("div","webhotkeys-head",e);createEl("strong","",t).textContent="Keyboard shortcuts";const i=createEl("input","webhotkeys-filter",t);i.type="search",i.placeholder="Filter…";const s=createEl("button","webhotkeys-close",t);s.textContent="✕",s.onclick=()=>this._hideHelp();const n=createEl("div","webhotkeys-body",e);return this.getGroups().forEach(({name:r,hotkeys:l})=>{r&&(createEl("h3","",n).textContent=r),l.forEach(h=>{const a=createEl("div","webhotkeys-row",n),c=createEl(this.options.remap?"button":"kbd","webhotkeys-key",a);c.textContent=h.clue,createEl("span","webhotkeys-hint",a).textContent=h.hint,this.options.remap&&this._makeEditable(a,c,h)})}),this.options.remap&&(createEl("p","webhotkeys-note",n).textContent="Click a combination to remap it."),i.oninput=()=>{const r=i.value.toLowerCase();n.querySelectorAll(".webhotkeys-row").forEach(l=>{l.style.display=l.textContent.toLowerCase().includes(r)?"":"none"})},document.body.appendChild(e),this._help=e,e.addEventListener("close",()=>this._hideHelp()),e.addEventListener("cancel",r=>this._recording&&r.preventDefault?.()),e.showModal(),this}_makeEditable(e,t,i){const s="Click and press your own combination";t.type="button";const n=createEl("button","webhotkeys-reset",e);n.textContent="↺",n.title="Back to the default combination";const r=(l=!1)=>{t.textContent=i.clue,t.className="webhotkeys-key";const h=i.combination!==i.defaultCombination;n.style.display=h?"":"none";const a=this.getConflicts().find(c=>c.combination===i.combination);e.className="webhotkeys-row"+(a?" webhotkeys-clash":""),t.title=a?`Also used by: ${a.hotkeys.filter(c=>c!==i).map(c=>c.hint).join(", ")}`:s,l&&t.focus?.()};r(),n.onclick=()=>{i.rebind(),r(!0)},t.onclick=()=>{if(this._recording)return this._recording();t.className="webhotkeys-key webhotkeys-recording",t.textContent="…",this.record(l=>{l!=="Escape"&&i.rebind(l),r(!0)},{sequence:!0,onProgress:l=>{if(l.split(" ").pop()==="Escape")return this._recording?.(),r(!0);t.textContent=l+" …"}})}}_hideHelp(){if(this._recording?.(),this._help){const e=this._help;this._help=null,e.close?.(),e.remove?.()}return this}_showHints(){if(typeof document>"u"||!document.body)return this;this._hideHints(),this._injectStyle();const e=createEl("div","webhotkeys-hints");return this.getHotkeys().forEach(t=>{const i=t.element;if(!i||!isVisible(i))return;const s=i.getBoundingClientRect?.();if(!s||!s.width&&!s.height)return;const n=createEl("kbd","webhotkeys-badge",e);n.textContent=t.clue,n.style.left=`${s.left+window.scrollX}px`,n.style.top=`${s.top+window.scrollY}px`}),document.body.appendChild(e),this._hints=e,this._dismissHints=()=>this._hideHints(),window.addEventListener("scroll",this._dismissHints,{passive:!0,once:!0}),window.addEventListener("resize",this._dismissHints,{once:!0}),this}_hideHints(){return this._hints&&(this._hints.remove?.(),this._hints=null,window.removeEventListener("scroll",this._dismissHints),window.removeEventListener("resize",this._dismissHints)),this}toggleHints(e=null){return e??!this._hints?this._showHints():this._hideHints()}_injectStyle(){this._style||typeof document>"u"||!document.head||(this._style=createEl("style"),this._style.textContent=`
9
9
  .webhotkeys-dialog { border: 0; border-radius: .5em; padding: 0; max-width: 40em; width: 90%; max-height: 80vh;
10
10
  box-shadow: 0 .5em 2em rgba(0,0,0,.35); font: inherit; background: Canvas; color: CanvasText; }
11
11
  .webhotkeys-dialog::backdrop { background: rgba(0,0,0,.4); }
@@ -31,4 +31,4 @@ button.webhotkeys-key:focus { outline: 2px solid currentColor; outline-offset: 1
31
31
  .webhotkeys-hints { position: absolute; inset: 0; pointer-events: none; z-index: 2147483000; }
32
32
  .webhotkeys-badge { position: absolute; transform: translate(-30%, -50%); pointer-events: none;
33
33
  background: #ffd76e; color: #222; border: 1px solid #b98d00; border-radius: .25em;
34
- padding: 0 .3em; font: bold 11px/1.5 monospace; white-space: nowrap; }`,document.head.appendChild(this._style))}getSheet(){return typeof this._sheet>"u"&&(this._sheet=(()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("")),document.head.appendChild(e),this._userStyle=e,e.sheet})()),this._sheet}_insertCss(e){this.getSheet().insertRule(e)}}class _List{constructor(e){this.query="div",this.currentSelector=":focus",this.onChange=null,this.onChanged=null,this.selected=null,this._wh=e,this.wrap=!1,this.scroll=!0,this.scope=null,this._hotkeys=[]}_configure(e,{current:t,css:i=null,wrap:s,scroll:n,onChange:r,onChanged:l,scope:a,upDown:h=!1,homeEnd:c=!1,typeahead:f=!1}={}){e!==void 0&&(this.query=e),t!==void 0&&(this.currentSelector=t,i&&this._wh._insertCss(this.query+this.currentSelector+i)),s!==void 0&&(this.wrap=s),n!==void 0&&(this.scroll=n),r!==void 0&&(this.onChange=r),l!==void 0&&(this.onChanged=l),a!==void 0&&(this.scope=a),h&&this._handleUpDown(),c&&this._handleHomeEnd(),f&&this._handleTypeahead(typeof f=="number"?f:800)}_handleUpDown(){this._hotkeys.push(this._wh.grab("ArrowUp","Lists up",()=>this.goPrev(),this.scope),this._wh.grab("ArrowDown","Lists down",()=>this.goNext(),this.scope))}_handleHomeEnd(){this._hotkeys.push(this._wh.grab("Home","Lists first",()=>this.goFirst(),this.scope),this._wh.grab("End","Lists last",()=>this.goLast(),this.scope))}_handleTypeahead(e=800){let t="",i=0;this._typeahead=s=>{if(s.key?.length!==1||s.ctrlKey||s.altKey||s.metaKey||this._wh._isTextContext(s,this._wh.activeElement()))return;const n=Date.now();t=(n-i>e?"":t)+s.key.toLowerCase(),i=n,this.selectByPrefix(t)&&(s.preventDefault(),s.stopPropagation())},document.addEventListener("keydown",this._typeahead,!0)}selectByPrefix(e){this._loadSiblings();const t=Array.from(this.items||[]).find(i=>(i.innerText||i.textContent||"").trim().toLowerCase().startsWith(e));return t&&this._change(t,this.selected),!!t}destroy(){return this._typeahead&&(document.removeEventListener("keydown",this._typeahead,!0),this._typeahead=null),this._hotkeys.forEach(e=>e?.remove()),this._hotkeys=[],this}_loadSiblings(e=1){if(this.items=document.querySelectorAll(this.query),!this.items.length)return!1;for(let t of document.querySelectorAll(this.query))t.matches(this.currentSelector)&&(this.selected=t);if(this.selected){const t=this.items.length;for(let i=0;i<t;i++)if(this.selected.isSameNode(this.items[i]))return this.prev=this.items[this.wrap?_wrapIndex(i,-e,t):_clampIndex(i,-e,t)],this.next=this.items[this.wrap?_wrapIndex(i,e,t):_clampIndex(i,e,t)],!0}else return this.prev=this.next=this.selected=this.items[0],!0;return!1}get current(){return this._loadSiblings(),this.selected}set current(e){this._loadSiblings()&&(this._change(e),this._loadSiblings()||console.error("WebHotkeys.js> Could not change successfully to:",e))}goNext(e){return this._loadSiblings(e)?this._change(this.next,this.selected):!1}goPrev(e){return this._loadSiblings(e)?this._change(this.prev,this.selected):!1}goFirst(){return this._loadSiblings()?this._change(this.items[0],this.selected):!1}goLast(){return this._loadSiblings()?this._change(this.items[this.items.length-1],this.selected):!1}go(e=!0,t=1){return this._loadSiblings(t)?this._change(e?this.next:this.prev,this.selected):!1}_change(e,t){return _applyChange(this,e,t)}}class _Grid{constructor(e,t,i,{current:s=":focus",wrap:n=!1,scroll:r=!0,onChange:l=null,onChanged:a=null,scope:h=null}={}){this._wh=e,this.rowQuery=t,this.cellQuery=i,this.currentSelector=s,this.wrap=n,this.scroll=r,this.onChange=l,this.onChanged=a,this.selected=null,this._hotkeys=[this._wh.grab("ArrowUp","Grid up",()=>this.go(-1,0),h),this._wh.grab("ArrowDown","Grid down",()=>this.go(1,0),h),this._wh.grab("ArrowLeft","Grid left",()=>this.go(0,-1),h),this._wh.grab("ArrowRight","Grid right",()=>this.go(0,1),h)]}_loadPosition(){if(this.rows=Array.from(document.querySelectorAll(this.rowQuery)),!this.rows.length)return!1;const e=this.currentSelector.indexOf(":focus")===0&&this._wh.activeElement();for(let i=0;i<this.rows.length;i++){const s=this.rows[i].querySelectorAll(this.cellQuery);for(let n=0;n<s.length;n++)if(s[n].matches(this.currentSelector)||e&&s[n].contains?.(e))return this.rowIndex=i,this.colIndex=n,this.selected=s[n],!0}const t=this.rows[0].querySelectorAll(this.cellQuery);return t.length?(this.rowIndex=0,this.colIndex=0,this.selected=t[0],!0):!1}go(e=0,t=0){if(!this._loadPosition())return!1;const i=this.selected,s=e?this.wrap?_wrapIndex(this.rowIndex,e,this.rows.length):_clampIndex(this.rowIndex,e,this.rows.length):this.rowIndex,n=this.rows[s].querySelectorAll(this.cellQuery);if(!n.length)return!1;const r=t?this.wrap?_wrapIndex(this.colIndex,t,n.length):_clampIndex(this.colIndex,t,n.length):Math.min(this.colIndex,n.length-1);return _applyChange(this,n[r],i)}destroy(){return this._hotkeys.forEach(e=>e?.remove()),this}}function isString(o){return typeof o=="string"||o instanceof String}function _wrapIndex(o,e,t){return((o+e)%t+t)%t}function _clampIndex(o,e,t){return Math.min(Math.max(o+e,0),t-1)}function _applyChange(o,e,t){let i=!0;if(typeof o.onChange=="function"&&(i=o.onChange(e,t)),i){if(o.currentSelector.substr(0,1)==="."){let s=o.currentSelector.substr(1);t&&t.classList.remove(s),e&&e.classList.add(s)}else if(o.currentSelector.substring(0,1)==="["){const s=o.currentSelector.substring(1,o.currentSelector.length-1);t&&t.removeAttribute(s),e&&e.setAttribute(s,"1")}else if(o.currentSelector.indexOf(":focus")===0)e.focus();else return console.error("WebHotkeys.js> Don't know how to process selector type:",o.currentSelector),!1;o.selected=e,o.scroll&&e?.scrollIntoView?.({block:"nearest"}),o.onChanged&&o.onChanged(e)}return!0}function parseRemapping(o){let e;try{e=JSON.parse(o)}catch{return null}return!e||typeof e!="object"||Array.isArray(e)?null:Object.values(e).every(isString)?e:null}function isSafeCombination(o){return!isString(o)||!o.trim()?!1:o.split(" ").filter(e=>e.length).every(e=>{const t=e.split("+");t[t.length-1]===""&&t[t.length-2]===""&&t.splice(t.length-2,2,"+");const i=t.pop();return(i.length===1||/^[A-Za-z0-9]+$/.test(i))&&t.every(s=>MODIFIER_ALIASES[s.toLowerCase()])})}const NAMED_CODES=/^(Arrow(Up|Down|Left|Right)|Home|End|Delete|Backspace|Tab|Enter|Escape|Insert|Space|PageUp|PageDown|F\d{1,2})$/;function completeSimulatedEvent(o){if(o.code===void 0||o.key!==void 0)return o;const e=/^Digit(\d)$/.exec(o.code);if(e)return{...o,key:e[1]};const t=/^Key([A-Z])$/.exec(o.code);return t?{...o,key:t[1].toLowerCase()}:NAMED_CODES.test(o.code)?{...o,key:o.code}:o}function pickModifiers(o){return{ctrlKey:!!o.ctrlKey,shiftKey:!!o.shiftKey,altKey:!!o.altKey,metaKey:!!o.metaKey}}function keyEquals(o,e){return o===e||o?.length===1&&e?.length===1&&o.toLowerCase()===e.toLowerCase()}function isVisible(o){return o.getClientRects===void 0&&o.checkVisibility===void 0?!0:o.hidden||o.closest?.("[inert],[hidden]")?!1:typeof o.checkVisibility=="function"?o.checkVisibility():!!(o.offsetWidth||o.offsetHeight||o.getClientRects?.().length)}function createEl(o,e="",t=null){if(typeof document>"u"||!document.createElement)return null;const i=document.createElement(o);return e&&(i.className=e),t?.appendChild(i),i}typeof document<"u"&&document.currentScript&&document.currentScript.dataset.register!==void 0&&(window.webHotkeys=new WebHotkeys),typeof module<"u"&&module.exports?(module.exports=WebHotkeys,module.exports.WebHotkeys=WebHotkeys,module.exports.Hotkey=Hotkey,module.exports.HotkeyGroup=HotkeyGroup):typeof window<"u"&&(window.WebHotkeys=WebHotkeys,window.Hotkey=Hotkey,window.HotkeyGroup=HotkeyGroup);
34
+ padding: 0 .3em; font: bold 11px/1.5 monospace; white-space: nowrap; }`,document.head.appendChild(this._style))}getSheet(){return typeof this._sheet>"u"&&(this._sheet=(()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("")),document.head.appendChild(e),this._userStyle=e,e.sheet})()),this._sheet}_insertCss(e){this.getSheet().insertRule(e)}}class _List{constructor(e){this.query="div",this.currentSelector=":focus",this.onChange=null,this.onChanged=null,this.selected=null,this._wh=e,this.wrap=!1,this.scroll=!0,this.scope=null,this._hotkeys=[]}_configure(e,{current:t,css:i=null,wrap:s,scroll:n,onChange:r,onChanged:l,scope:h,upDown:a=!1,homeEnd:c=!1,typeahead:f=!1}={}){e!==void 0&&(this.query=e),t!==void 0&&(this.currentSelector=t,i&&this._wh._insertCss(this.query+this.currentSelector+i)),s!==void 0&&(this.wrap=s),n!==void 0&&(this.scroll=n),r!==void 0&&(this.onChange=r),l!==void 0&&(this.onChanged=l),h!==void 0&&(this.scope=h),a&&this._handleUpDown(),c&&this._handleHomeEnd(),f&&this._handleTypeahead(typeof f=="number"?f:800)}_handleUpDown(){this._hotkeys.push(this._wh.grab("ArrowUp","Lists up",()=>this.goPrev(),this.scope),this._wh.grab("ArrowDown","Lists down",()=>this.goNext(),this.scope))}_handleHomeEnd(){this._hotkeys.push(this._wh.grab("Home","Lists first",()=>this.goFirst(),this.scope),this._wh.grab("End","Lists last",()=>this.goLast(),this.scope))}_handleTypeahead(e=800){let t="",i=0;this._typeahead=s=>{if(s.key?.length!==1||s.ctrlKey||s.altKey||s.metaKey||this._wh._isTextContext(s,this._wh.activeElement()))return;const n=Date.now();t=(n-i>e?"":t)+s.key.toLowerCase(),i=n,this.selectByPrefix(t)&&(s.preventDefault(),s.stopPropagation())},document.addEventListener("keydown",this._typeahead,!0)}selectByPrefix(e){this._loadSiblings();const t=Array.from(this.items||[]).find(i=>(i.innerText||i.textContent||"").trim().toLowerCase().startsWith(e));return t&&this._change(t,this.selected),!!t}destroy(){return this._typeahead&&(document.removeEventListener("keydown",this._typeahead,!0),this._typeahead=null),this._hotkeys.forEach(e=>e?.remove()),this._hotkeys=[],this}_loadSiblings(e=1){if(this.items=document.querySelectorAll(this.query),!this.items.length)return!1;for(let t of document.querySelectorAll(this.query))t.matches(this.currentSelector)&&(this.selected=t);if(this.selected){const t=this.items.length;for(let i=0;i<t;i++)if(this.selected.isSameNode(this.items[i]))return this.prev=this.items[this.wrap?_wrapIndex(i,-e,t):_clampIndex(i,-e,t)],this.next=this.items[this.wrap?_wrapIndex(i,e,t):_clampIndex(i,e,t)],!0}else return this.prev=this.next=this.selected=this.items[0],!0;return!1}get current(){return this._loadSiblings(),this.selected}set current(e){this._loadSiblings()&&(this._change(e),this._loadSiblings()||console.error("WebHotkeys.js> Could not change successfully to:",e))}goNext(e){return this._loadSiblings(e)?this._change(this.next,this.selected):!1}goPrev(e){return this._loadSiblings(e)?this._change(this.prev,this.selected):!1}goFirst(){return this._loadSiblings()?this._change(this.items[0],this.selected):!1}goLast(){return this._loadSiblings()?this._change(this.items[this.items.length-1],this.selected):!1}go(e=!0,t=1){return this._loadSiblings(t)?this._change(e?this.next:this.prev,this.selected):!1}_change(e,t){return _applyChange(this,e,t)}}class _Grid{constructor(e,t,i,{current:s=":focus",wrap:n=!1,scroll:r=!0,onChange:l=null,onChanged:h=null,scope:a=null}={}){this._wh=e,this.rowQuery=t,this.cellQuery=i,this.currentSelector=s,this.wrap=n,this.scroll=r,this.onChange=l,this.onChanged=h,this.selected=null,this._hotkeys=[this._wh.grab("ArrowUp","Grid up",()=>this.go(-1,0),a),this._wh.grab("ArrowDown","Grid down",()=>this.go(1,0),a),this._wh.grab("ArrowLeft","Grid left",()=>this.go(0,-1),a),this._wh.grab("ArrowRight","Grid right",()=>this.go(0,1),a)]}_loadPosition(){if(this.rows=Array.from(document.querySelectorAll(this.rowQuery)),!this.rows.length)return!1;const e=this.currentSelector.indexOf(":focus")===0&&this._wh.activeElement();for(let i=0;i<this.rows.length;i++){const s=this.rows[i].querySelectorAll(this.cellQuery);for(let n=0;n<s.length;n++)if(s[n].matches(this.currentSelector)||e&&s[n].contains?.(e))return this.rowIndex=i,this.colIndex=n,this.selected=s[n],!0}const t=this.rows[0].querySelectorAll(this.cellQuery);return t.length?(this.rowIndex=0,this.colIndex=0,this.selected=t[0],!0):!1}go(e=0,t=0){if(!this._loadPosition())return!1;const i=this.selected,s=e?this.wrap?_wrapIndex(this.rowIndex,e,this.rows.length):_clampIndex(this.rowIndex,e,this.rows.length):this.rowIndex,n=this.rows[s].querySelectorAll(this.cellQuery);if(!n.length)return!1;const r=t?this.wrap?_wrapIndex(this.colIndex,t,n.length):_clampIndex(this.colIndex,t,n.length):Math.min(this.colIndex,n.length-1);return _applyChange(this,n[r],i)}destroy(){return this._hotkeys.forEach(e=>e?.remove()),this}}function isString(o){return typeof o=="string"||o instanceof String}function _wrapIndex(o,e,t){return((o+e)%t+t)%t}function _clampIndex(o,e,t){return Math.min(Math.max(o+e,0),t-1)}function _applyChange(o,e,t){let i=!0;if(typeof o.onChange=="function"&&(i=o.onChange(e,t)),i){if(o.currentSelector.substr(0,1)==="."){let s=o.currentSelector.substr(1);t&&t.classList.remove(s),e&&e.classList.add(s)}else if(o.currentSelector.substring(0,1)==="["){const s=o.currentSelector.substring(1,o.currentSelector.length-1);t&&t.removeAttribute(s),e&&e.setAttribute(s,"1")}else if(o.currentSelector.indexOf(":focus")===0)e.focus();else return console.error("WebHotkeys.js> Don't know how to process selector type:",o.currentSelector),!1;o.selected=e,o.scroll&&e?.scrollIntoView?.({block:"nearest"}),o.onChanged&&o.onChanged(e)}return!0}function parseRemapping(o){let e;try{e=JSON.parse(o)}catch{return null}return!e||typeof e!="object"||Array.isArray(e)?null:Object.values(e).every(isString)?e:null}function isSafeCombination(o){return!isString(o)||!o.trim()?!1:o.split(" ").filter(e=>e.length).every(e=>{const t=e.split("+");t[t.length-1]===""&&t[t.length-2]===""&&t.splice(t.length-2,2,"+");const i=t.pop();return(i.length===1||/^[A-Za-z0-9]+$/.test(i))&&t.every(s=>MODIFIER_ALIASES[s.toLowerCase()])})}const NAMED_CODES=/^(Arrow(Up|Down|Left|Right)|Home|End|Delete|Backspace|Tab|Enter|Escape|Insert|Space|PageUp|PageDown|F\d{1,2})$/;function completeSimulatedEvent(o){if(o.code===void 0||o.key!==void 0)return o;const e=/^Digit(\d)$/.exec(o.code);if(e)return{...o,key:e[1]};const t=/^Key([A-Z])$/.exec(o.code);return t?{...o,key:t[1].toLowerCase()}:NAMED_CODES.test(o.code)?{...o,key:o.code}:o}function pickModifiers(o){return{ctrlKey:!!o.ctrlKey,shiftKey:!!o.shiftKey,altKey:!!o.altKey,metaKey:!!o.metaKey}}function keyEquals(o,e){return o===e||o?.length===1&&e?.length===1&&o.toLowerCase()===e.toLowerCase()}function isEditable(o){return isTextInput(o)||!!o.isContentEditable||o.contentEditable==="true"}function isVisible(o){return o.getClientRects===void 0&&o.checkVisibility===void 0?!0:o.hidden||o.closest?.("[inert],[hidden]")?!1:typeof o.checkVisibility=="function"?o.checkVisibility():!!(o.offsetWidth||o.offsetHeight||o.getClientRects?.().length)}function createEl(o,e="",t=null){if(typeof document>"u"||!document.createElement)return null;const i=document.createElement(o);return e&&(i.className=e),t?.appendChild(i),i}typeof document<"u"&&document.currentScript&&document.currentScript.dataset.register!==void 0&&(window.webHotkeys=new WebHotkeys),typeof module<"u"&&module.exports?(module.exports=WebHotkeys,module.exports.WebHotkeys=WebHotkeys,module.exports.Hotkey=Hotkey,module.exports.HotkeyGroup=HotkeyGroup):typeof window<"u"&&(window.WebHotkeys=WebHotkeys,window.Hotkey=Hotkey,window.HotkeyGroup=HotkeyGroup);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhotkeys",
3
- "version": "1.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "Easy solution to integrate keyboard hotkeys into the webpage.",
5
5
  "main": "src/WebHotkeys.js",
6
6
  "files": [
package/src/WebHotkeys.js CHANGED
@@ -16,6 +16,8 @@
16
16
  * @property {string} [actionAttribute='data-hotkey-action'] Attribute name to override what happens with the element ('click', 'focus', 'toggle', 'none'). Without it a text field is focused, a button/checkbox/radio clicked and a DETAILS toggled. @see defaultAction
17
17
  * @property {boolean} [inHidden=false] Let a hotkey fire even when its linked element is hidden. The default skips it, so a hidden panel does not swallow the combination; set it when the elements are mere affordances of the hotkeys (a fading toolbar). Overridable per hotkey. @see Hotkey.allowHidden
18
18
  * @property {?string|?function} [ignore=null] Selector or callback(activeElement, event). When it matches, no hotkey is triggered at all.
19
+ * @property {?string} [modal='dialog:modal, [aria-modal=true]'] Selector of the modal windows. While one of them is visible, only the hotkeys
20
+ * inside it fire (its element, or its scope, lies within the modal); the other keys go to the modal natively. Null turns the modal mode off.
19
21
  * @property {number} [sequenceTimeout=1000] Milliseconds a key sequence ('g i') may be spread over. Also how long the F1 dialog waits before committing a recorded sequence.
20
22
  * @property {boolean|string} [remap=true] The F1 dialog lets the user click a combination and press their own. A string is used as the localStorage key (true means 'webhotkeys.remap'), false turns the editing off.
21
23
  * @property {?function} [onRemap] Called with the remapping object whenever the user changes a combination. Handy to store the layout on the server. @see remapping
@@ -27,7 +29,7 @@ const WebHotkeysDefaults = {
27
29
  replaceAccesskeys: true, helpKey: "F1", help: "dialog", hintKey: "F2",
28
30
  attribute: "data-hotkey", groupAttribute: "data-hotkey-group", actionAttribute: "data-hotkey-action",
29
31
  observe: true, onToggle: null, onTrigger: null, onMiss: null, hint: "title",
30
- ignore: null, sequenceTimeout: 1000, mac: null, warnConflicts: false, inHidden: false,
32
+ ignore: null, modal: "dialog:modal, [aria-modal=true]", sequenceTimeout: 1000, mac: null, warnConflicts: false, inHidden: false,
31
33
  remap: true, onRemap: null
32
34
  }
33
35
 
@@ -58,12 +60,34 @@ const FORM_TAGS = ["INPUT", "SELECT", "TEXTAREA"]
58
60
  /** Input types that are not a text field - they never eat a letter key, so the text guard must not stand back for them. */
59
61
  const NON_TEXT_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file", "range", "color"]
60
62
  /**
61
- * Keys that a control which is no text field still handles itself. A range moves its thumb with
62
- * Left/Right/Home/End, so these must not trigger a hotkey (ex: a grid stepping to the next cell).
63
- * Up/Down stay free on purpose: a horizontal slider is reached for along its own axis, and in a
64
- * grid the vertical arrows are what gets the user out of the cell again.
63
+ * Keys that a focused control which is no text field still handles itself (without Ctrl, Alt, Meta).
64
+ *
65
+ * A range moves its thumb with Left/Right/Home/End, so these must not trigger a hotkey (ex: a grid
66
+ * stepping to the next cell). Up/Down stay free on purpose: a horizontal slider is reached for along
67
+ * its own axis, and in a grid the vertical arrows are what gets the user out of the cell again.
68
+ *
69
+ * Enter and Space press a focused button, Enter follows a focused link (Space on a link merely scrolls
70
+ * the page, so it stays a hotkey), Space ticks a checkbox or a radio (Enter does nothing there).
71
+ * Only a hotkey with `inInput` takes the key over from the control.
72
+ * @param {?HTMLElement} el The focused element.
73
+ * @returns {?string[]} The `event.key` values the control keeps.
65
74
  */
66
- const CONTROL_KEYS = { range: ["ArrowLeft", "ArrowRight", "Home", "End"] }
75
+ const controlKeys = el => {
76
+ const type = el?.tagName === "INPUT" && el.type
77
+ if (type === "range") {
78
+ return ["ArrowLeft", "ArrowRight", "Home", "End"]
79
+ }
80
+ if (el?.tagName === "BUTTON" || el?.tagName === "SUMMARY" || ["button", "submit", "reset"].includes(type)) {
81
+ return ["Enter", " "]
82
+ }
83
+ if (type === "checkbox" || type === "radio") {
84
+ return [" "]
85
+ }
86
+ if (el?.tagName === "A" && el.href) {
87
+ return ["Enter"]
88
+ }
89
+ return null
90
+ }
67
91
  /** Input types a hotkey should activate instead of merely focusing (a range or a color still wants the focus - the arrows adjust it). */
68
92
  const CLICKABLE_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file"]
69
93
  /** Is the element a text field, ie. would a letter key land in it? (A SELECT counts - letters do its typeahead.) */
@@ -489,6 +513,10 @@ class WebHotkeys {
489
513
  this._recording = null
490
514
  /** @type {_List[]} Every `list()` instance, so `destroy()` can detach their typeahead listeners too. */
491
515
  this._lists = []
516
+ /** @type {Array[]} One entry per pending `suspend()`: what that call lets through. */
517
+ this._suspensions = []
518
+ /** @type {?{event: KeyEvent, field: HTMLElement}} Escape the capture phase left to a text field. @see _fallback */
519
+ this._yielded = null
492
520
 
493
521
  // Object.create(null) (not {}) because the group name is an arbitrary string coming from
494
522
  // [data-hotkey-group] in the DOM. A group named e.g. "constructor" or "__proto__" would otherwise
@@ -569,6 +597,11 @@ class WebHotkeys {
569
597
  //
570
598
  this._listener = e => this._trigger(e)
571
599
  document.addEventListener("keydown", this._listener, true)
600
+ // Bubble phase on the window, so that it runs after the page's own bubble handlers on the document.
601
+ this._fallbackListener = e => this._fallback(e)
602
+ if (typeof window !== "undefined") {
603
+ window.addEventListener?.("keydown", this._fallbackListener)
604
+ }
572
605
  return this
573
606
  }
574
607
 
@@ -588,6 +621,9 @@ class WebHotkeys {
588
621
  */
589
622
  destroy() {
590
623
  document.removeEventListener("keydown", this._listener, true)
624
+ if (typeof window !== "undefined") {
625
+ window.removeEventListener?.("keydown", this._fallbackListener)
626
+ }
591
627
  this._observer?.disconnect()
592
628
  this._recording?.()
593
629
  this._hideHelp()
@@ -599,6 +635,8 @@ class WebHotkeys {
599
635
  this._groups = Object.create(null)
600
636
  this._dom = new WeakMap()
601
637
  this._buffer = []
638
+ this._suspensions = []
639
+ this._yielded = null
602
640
  this._settleDeferred(false)
603
641
  this._style?.remove?.()
604
642
  this._style = this._sheet = undefined
@@ -629,6 +667,80 @@ class WebHotkeys {
629
667
  return el || null
630
668
  }
631
669
 
670
+ /**
671
+ * Silence every hotkey until the returned `release` is called, ex. while the application shows
672
+ * a modal of its own. Nothing is disabled meanwhile, so the hotkeys keep their enabled state
673
+ * (whatever got enabled or disabled meanwhile stays so) and their order of priority.
674
+ * The calls nest: the hotkeys come back with the last pending `release()`.
675
+ * @param {?(string|HotkeyGroup|Hotkey|Array<string|HotkeyGroup|Hotkey>)} except Groups (their names or
676
+ * the objects) or single hotkeys that keep working. A group name is resolved at the keystroke time,
677
+ * so the group may be populated later.
678
+ * @returns {function} release. Calling it again does nothing.
679
+ * @example const release = wh.suspend("Dialog"); ...; release()
680
+ */
681
+ suspend(except = null) {
682
+ const entry = !except ? [] : (Array.isArray(except) && !(except instanceof HotkeyGroup) ? except : [except])
683
+ this._suspensions.push(entry)
684
+ return () => {
685
+ const index = this._suspensions.indexOf(entry)
686
+ if (index > -1) {
687
+ this._suspensions.splice(index, 1)
688
+ }
689
+ }
690
+ }
691
+
692
+ /** @returns {boolean} Some `suspend()` has not been released yet. */
693
+ get suspended() {
694
+ return this._suspensions.length > 0
695
+ }
696
+
697
+ /**
698
+ * The modal window on top, if any is visible. @see WebHotkeysDefaults.modal
699
+ * @returns {?HTMLElement}
700
+ */
701
+ _modal() {
702
+ const { modal } = this.options
703
+ if (!modal || typeof document === "undefined") {
704
+ return null
705
+ }
706
+ try {
707
+ return Array.from(document.querySelectorAll(modal)).filter(isVisible).pop() || null
708
+ } catch (e) { // a selector the browser does not understand
709
+ return null
710
+ }
711
+ }
712
+
713
+ /**
714
+ * May the hotkey fire now, considering `suspend()` and the modal mode?
715
+ * A hotkey belongs to the modal when its element lies within, or its scope does
716
+ * (a function scope cannot tell, so it counts when the focus is within the modal).
717
+ * @param {Hotkey} hotkey
718
+ * @param {?HTMLElement} active
719
+ * @param {?HTMLElement} modal
720
+ * @returns {boolean}
721
+ */
722
+ _admits(hotkey, active, modal) {
723
+ if (!this._suspensions.every(except => except.some(item => item === hotkey
724
+ || (isString(item) ? this._groups[item] : item)?.includes?.(hotkey)))) {
725
+ return false
726
+ }
727
+ if (!modal) {
728
+ return true
729
+ }
730
+ const { element, scope } = hotkey
731
+ if (element) {
732
+ return modal.contains(element)
733
+ }
734
+ if (!scope) {
735
+ return false
736
+ }
737
+ if (isString(scope)) {
738
+ const within = active?.closest?.(scope)
739
+ return !!within && modal.contains(within)
740
+ }
741
+ return modal.contains(typeof scope === "function" ? active : scope)
742
+ }
743
+
632
744
  /**
633
745
  * @param {boolean} enabledOnly
634
746
  * @returns {Hotkey[]}
@@ -1025,32 +1137,38 @@ class WebHotkeys {
1025
1137
  }
1026
1138
 
1027
1139
  /**
1028
- * Is the user typing right now? Then a plain letter or a caret movement is none of our business.
1140
+ * Does the focused element own the keystroke? The user typing makes a plain letter or a caret
1141
+ * movement none of our business, a focused control keeps the keys it handles itself.
1142
+ * Only the hotkeys with `inInput` fire then. @see controlKeys
1029
1143
  * @param {KeyEvent} e
1030
1144
  * @param {?HTMLElement} active
1031
1145
  * @returns {boolean}
1032
1146
  */
1033
1147
  _isTextContext(e, active) {
1034
- const controlKeys = active?.tagName === "INPUT" && CONTROL_KEYS[active.type]
1035
- if (controlKeys) {
1036
- return !e.altKey && !e.metaKey && !e.ctrlKey && controlKeys.includes(e.key)
1148
+ if (!e.altKey && !e.metaKey && !e.ctrlKey && controlKeys(active)?.includes(e.key)) {
1149
+ return true
1037
1150
  }
1038
1151
  return !e.altKey
1039
1152
  && !e.metaKey
1040
- && (// this is a mere letter (not Escape, F1... which anticipate a hotkey)
1153
+ && (// this is a mere letter (not F1... which anticipates a hotkey)
1041
1154
  e.key?.length === 1
1042
1155
  // or a text editing keys that can take use of Ctrl (Left and Ctrl+Left is text editing)
1043
1156
  || ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "Delete", "Backspace"].includes(e.key)
1044
- // or a text editing key that cannot take use of Ctrl (Enter is text editing, Ctrl+Enter is not)
1045
- || ["Tab", "Enter"].includes(e.key) && !e.ctrlKey
1157
+ // or a text editing key that cannot take use of Ctrl (Enter is text editing, Ctrl+Enter is not).
1158
+ // Escape belongs to the field first (a palette closing, an inline editor cancelling);
1159
+ // the hotkey gets it afterwards, unless the field used it. @see _fallback
1160
+ || ["Tab", "Enter", "Escape"].includes(e.key) && !e.ctrlKey
1046
1161
  )
1047
1162
  // We are in a text editing context. Either a form tag like INPUT or within an editable element.
1048
1163
  && !!active
1049
- && (isTextInput(active) || active.contentEditable === "true")
1164
+ && isEditable(active)
1050
1165
  }
1051
1166
 
1052
1167
  /**
1053
- * Hotkeys possibly matching the keystroke, the most recently grabbed first.
1168
+ * Hotkeys possibly matching the keystroke, in the order they are tried:
1169
+ * the longer sequence first ('g i' beats 'i'), then a hotkey matched directly before one reached
1170
+ * through the numpad fallback, then a hotkey having a scope before a scope-less one (the more
1171
+ * specific wins, whatever the order of grabbing), and then the most recently grabbed (or enabled) first.
1054
1172
  *
1055
1173
  * First check whether a `code` hotkey was defined (`Alt+Digit1`).
1056
1174
  * If not, try its `key` property (`Alt+1` (EN) or `Alt++` (CZ)).
@@ -1073,13 +1191,21 @@ class WebHotkeys {
1073
1191
  states.push((oneChar && /[A-Z]/.test(e.key) ? e.key.toLowerCase() : e.key)
1074
1192
  + Hotkey.mod_state(e, oneChar && !/[A-Za-z]/.test(e.key)))
1075
1193
  }
1194
+ if (states[0] === states[1]) { // a named key, its `key` equals its `code` ('Escape'): try the bucket once
1195
+ states.pop()
1196
+ }
1197
+ const direct = states.length
1076
1198
  if (CODE_ALIASES[e.code]) { // shadow combination, tried only when nothing else matched
1077
1199
  states.push(CODE_ALIASES[e.code] + Hotkey.mod_state(e))
1078
1200
  }
1079
- return states.flatMap(state => this._hotkeys[state]?.filter(hotkey => hotkey.enabled) || [])
1080
- // A sequence is more specific than a plain hotkey of the same last key ('g i' beats 'i').
1081
- // The sort is stable, so hotkeys of the same length keep the most-recently-grabbed-first order.
1082
- .sort((a, b) => b.sequence.length - a.sequence.length)
1201
+ return states.flatMap((state, i) => (this._hotkeys[state] || [])
1202
+ .filter(hotkey => hotkey.enabled)
1203
+ .map(hotkey => ({ hotkey, alias: i >= direct })))
1204
+ // The sort is stable, so the ties keep the most-recently-grabbed-first order of the registry.
1205
+ .sort((a, b) => (b.hotkey.sequence.length - a.hotkey.sequence.length)
1206
+ || (a.alias - b.alias)
1207
+ || (!!b.hotkey.scope - !!a.hotkey.scope))
1208
+ .map(({ hotkey }) => hotkey)
1083
1209
  }
1084
1210
 
1085
1211
  /**
@@ -1106,9 +1232,13 @@ class WebHotkeys {
1106
1232
  return true
1107
1233
  }
1108
1234
 
1109
- /** @returns {boolean} The buffer is a beginning of some sequence – swallow the key and wait for the rest. */
1110
- _pendingSequence(now) {
1111
- return this.getHotkeys().some(hotkey => hotkey.sequence.length > this._buffer.length
1235
+ /**
1236
+ * @param {number} now
1237
+ * @param {function(Hotkey): boolean} admits
1238
+ * @returns {boolean} The buffer is a beginning of some sequence – swallow the key and wait for the rest.
1239
+ */
1240
+ _pendingSequence(now, admits) {
1241
+ return this.getHotkeys().some(hotkey => admits(hotkey) && hotkey.sequence.length > this._buffer.length
1112
1242
  && this._buffer.every((entry, i) => now - entry.time <= this.options.sequenceTimeout
1113
1243
  && Hotkey.match(hotkey.sequence[i], entry.event)))
1114
1244
  }
@@ -1116,11 +1246,12 @@ class WebHotkeys {
1116
1246
  /**
1117
1247
  * @param {KeyEvent} e The keystroke under consideration - not pushed into `_buffer` yet.
1118
1248
  * @param {number} now
1249
+ * @param {function(Hotkey): boolean} admits
1119
1250
  * @returns {boolean} Would `_buffer` plus `e` still be a live prefix of some longer registered sequence?
1120
1251
  * (Ex: a plain 'g' hotkey next to a grabbed 'g i' sequence - 'g' alone must not fire it right away.)
1121
1252
  */
1122
- _matchesPrefix(e, now) {
1123
- return this.getHotkeys().some(hotkey => hotkey.sequence.length > this._buffer.length + 1
1253
+ _matchesPrefix(e, now, admits) {
1254
+ return this.getHotkeys().some(hotkey => admits(hotkey) && hotkey.sequence.length > this._buffer.length + 1
1124
1255
  && this._buffer.every((entry, i) => now - entry.time <= this.options.sequenceTimeout
1125
1256
  && Hotkey.match(hotkey.sequence[i], entry.event))
1126
1257
  && Hotkey.match(hotkey.sequence[this._buffer.length], e))
@@ -1163,15 +1294,19 @@ class WebHotkeys {
1163
1294
  * deferred plain hotkey (see `_deferPlainHotkey`) may run well after its keystroke happened.
1164
1295
  * @param {Hotkey} hotkey
1165
1296
  * @param {KeyEvent} e
1297
+ * @param {?HTMLElement} modal The modal on top, @see _modal. (Looked up when not given.)
1166
1298
  * @returns {boolean} Whether the hotkey fired. False lets the caller try the next candidate.
1167
1299
  */
1168
- _fireHotkey(hotkey, e) {
1300
+ _fireHotkey(hotkey, e, modal = this._modal()) {
1169
1301
  const { action, element, scope } = hotkey
1170
1302
  const active = this.activeElement()
1303
+ if (!this._admits(hotkey, active, modal)) {
1304
+ return false // suspended, or outside the modal on top
1305
+ }
1171
1306
  // check we are in an allowed scope (the focused element has hotkey.scope for the ancestor)
1172
1307
  if (scope && !( // The scope is either a selector or a function or an HTMLElement
1173
1308
  isString(scope) ? active?.closest?.(scope)
1174
- : (scope instanceof Function ? scope.call(this, active, e)
1309
+ : (typeof scope === "function" ? scope.call(this, active, e)
1175
1310
  : scope.contains?.(active)))) {
1176
1311
  return false // not allowed scope
1177
1312
  }
@@ -1201,7 +1336,7 @@ class WebHotkeys {
1201
1336
  }
1202
1337
 
1203
1338
  /**
1204
- *
1339
+ * The keydown listener, capture phase.
1205
1340
  * @param {KeyEvent} e
1206
1341
  * @returns {undefined|boolean}
1207
1342
  */
@@ -1209,6 +1344,7 @@ class WebHotkeys {
1209
1344
  if (this._destroyed) {
1210
1345
  return
1211
1346
  }
1347
+ this._yielded = null
1212
1348
  if (this._recording) {
1213
1349
  return // `record` is capturing the keystroke; even Escape and F1 belong to it
1214
1350
  }
@@ -1230,21 +1366,69 @@ class WebHotkeys {
1230
1366
  // an input field has precedence over shorcuts
1231
1367
  // Ex: arrow hotkeys must not work, these control text caret
1232
1368
  const typing = this._isTextContext(e, active)
1369
+ const fired = this._dispatch(e, active, typing ? "typing" : "normal")
1370
+ if (typing && !fired && e.key === "Escape") {
1371
+ // The field gets the Escape first; unless it uses it, the hotkeys get it afterwards.
1372
+ this._yielded = { event: e, field: active }
1373
+ }
1374
+ return fired
1375
+ }
1376
+
1377
+ /**
1378
+ * The keydown listener, bubble phase on the window. Gives the hotkeys the Escape the capture phase
1379
+ * left to a text field - when nothing on the way used it (neither called `preventDefault`,
1380
+ * nor stopped the propagation, in which case we would not be reached at all).
1381
+ *
1382
+ * Why only Escape: it has no default action in a text field, so the hotkey's `preventDefault`
1383
+ * spoils nothing here. Enter inserts a line or submits a form, so it is left to the field entirely.
1384
+ * @param {KeyEvent} e
1385
+ * @returns {undefined|boolean}
1386
+ */
1387
+ _fallback(e) {
1388
+ const yielded = this._yielded
1389
+ if (!yielded || yielded.event !== e) {
1390
+ return
1391
+ }
1392
+ this._yielded = null
1393
+ if (this._destroyed || e.defaultPrevented) {
1394
+ return
1395
+ }
1396
+ // Not re-checked against the current focus: the field may have blurred itself meanwhile.
1397
+ const { field } = yielded
1398
+ if (field.tagName === "INPUT" && field.type === "search" && field.value) {
1399
+ return // the browser clears the search field only after the event, our preventDefault would stop it
1400
+ }
1401
+ return this._dispatch(e, this.activeElement(), "fallback")
1402
+ }
1403
+
1404
+ /**
1405
+ * Find and fire the hotkey of the keystroke.
1406
+ * @param {KeyEvent} e
1407
+ * @param {?HTMLElement} active
1408
+ * @param {string} mode 'normal'; 'typing' when the focused element owns the key (only `inInput` hotkeys
1409
+ * are tried); 'fallback' when the hotkeys get an Escape a text field did not use (the `inInput` ones
1410
+ * were tried already).
1411
+ * @returns {undefined|boolean} The hotkey fired.
1412
+ */
1413
+ _dispatch(e, active, mode) {
1414
+ const typing = mode === "typing"
1233
1415
  const now = Date.now()
1416
+ const modal = this._modal()
1417
+ const admits = hotkey => this._admits(hotkey, active, modal)
1234
1418
 
1235
1419
  for (const hotkey of this._candidates(e)) {
1236
- if (typing && !hotkey.allowInput) {
1420
+ if (typing ? !hotkey.allowInput : mode === "fallback" && hotkey.allowInput) {
1237
1421
  continue
1238
1422
  }
1239
1423
  if (hotkey.sequence.length > 1 && !this._matchesSequence(hotkey, now)) {
1240
1424
  continue // the preceding keystrokes were something else
1241
1425
  }
1242
- if (hotkey.sequence.length === 1 && this._matchesPrefix(e, now)) {
1426
+ if (hotkey.sequence.length === 1 && admits(hotkey) && this._matchesPrefix(e, now, admits)) {
1243
1427
  this._deferPlainHotkey(hotkey, e)
1244
1428
  continue // let the code below swallow the key and wait to see if the sequence completes
1245
1429
  }
1246
1430
 
1247
- if (this._fireHotkey(hotkey, e)) {
1431
+ if (this._fireHotkey(hotkey, e, modal)) {
1248
1432
  this._settleDeferred(false) // a hotkey just fired (likely the sequence this deferred one shadows) - drop it
1249
1433
  return true
1250
1434
  }
@@ -1257,7 +1441,7 @@ class WebHotkeys {
1257
1441
  while (this._buffer.length && (this._buffer.length > 8 || now - this._buffer[0].time > this.options.sequenceTimeout)) {
1258
1442
  this._buffer.shift()
1259
1443
  }
1260
- if (this._pendingSequence(now)) {
1444
+ if (this._pendingSequence(now, admits)) {
1261
1445
  e.preventDefault?.() // ex: 'g' of the 'g i' sequence must not scroll the page
1262
1446
  e.stopPropagation?.()
1263
1447
  return
@@ -1308,10 +1492,16 @@ class WebHotkeys {
1308
1492
  * @param {Key|KeyEvent} hotkey Ex: 'Ctrl+j' or a sequence 'g i' or a KeyEvent-like object.
1309
1493
  */
1310
1494
  simulate(hotkey) {
1495
+ const run = event => {
1496
+ event = completeSimulatedEvent(event)
1497
+ const fired = this._trigger(event)
1498
+ // A crafted event is never dispatched, so nothing would reach the bubble phase - do it here.
1499
+ return this._yielded?.event === event ? this._fallback(event) : fired
1500
+ }
1311
1501
  if (hotkey.constructor === String) {
1312
- return this._parseSequence(hotkey).map(event => this._trigger(completeSimulatedEvent(event))).pop()
1502
+ return this._parseSequence(hotkey).map(run).pop()
1313
1503
  }
1314
- return this._trigger(completeSimulatedEvent(hotkey))
1504
+ return run(hotkey)
1315
1505
  }
1316
1506
 
1317
1507
  //
@@ -2075,6 +2265,15 @@ function keyEquals(a, b) {
2075
2265
  return a === b || (a?.length === 1 && b?.length === 1 && a.toLowerCase() === b.toLowerCase())
2076
2266
  }
2077
2267
 
2268
+ /**
2269
+ * Would a keystroke edit the element? A text field or a contenteditable (inherited, or 'plaintext-only' too).
2270
+ * @param {HTMLElement} el
2271
+ * @returns {boolean}
2272
+ */
2273
+ function isEditable(el) {
2274
+ return isTextInput(el) || !!el.isContentEditable || el.contentEditable === "true"
2275
+ }
2276
+
2078
2277
  /**
2079
2278
  * A hidden element must not swallow its hotkey.
2080
2279
  * @param {HTMLElement} el
package/src/index.d.ts CHANGED
@@ -42,6 +42,10 @@ export interface WebHotkeysOptions {
42
42
  actionAttribute?: string
43
43
  /** Selector or predicate. While it matches the focused element, no hotkey fires at all. */
44
44
  ignore?: string | ((this: WebHotkeys, active: HTMLElement | null, event: KeyboardEvent) => boolean) | null
45
+ /** Selector of the modal windows. While one is visible, only the hotkeys within it fire (their element
46
+ * or scope lies within); other keys go to the modal natively. `null` turns it off.
47
+ * @default "dialog:modal, [aria-modal=true]" */
48
+ modal?: string | null
45
49
  /** Milliseconds a key sequence ("g i") may be spread over. Also the pause committing a recorded sequence. */
46
50
  sequenceTimeout?: number
47
51
  /** Let the user rebind the combinations right in the F1 dialog. A string is the localStorage key
@@ -184,6 +188,13 @@ export declare class WebHotkeys {
184
188
  * independent instance, so several tables can coexist on one page. */
185
189
  grid(rowQuery: string, cellQuery: string, options?: GridOptions): HotkeyGrid
186
190
 
191
+ /** Silence every hotkey until the returned `release` is called, keeping their enabled state and order.
192
+ * The calls nest: the hotkeys come back with the last pending release. `except` keeps working:
193
+ * group names (resolved at the keystroke time), groups or single hotkeys. */
194
+ suspend(except?: string | HotkeyGroup | Hotkey | Array<string | HotkeyGroup | Hotkey> | null): () => void
195
+ /** Some `suspend()` has not been released yet. */
196
+ readonly suspended: boolean
197
+
187
198
  /** Manually fire a combination or a whole sequence. */
188
199
  simulate(hotkey: Key | KeyEvent): boolean | undefined
189
200