webhotkeys 1.1.0 → 1.1.1
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 +2 -2
- package/dist/WebHotkeys.min.js +4 -4
- package/package.json +1 -1
- package/src/WebHotkeys.js +17 -1
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.
|
|
7
|
-
integrity="sha384-
|
|
6
|
+
<script src="https://cdn.jsdelivr.net/npm/webhotkeys@1.1.1/dist/WebHotkeys.min.js"
|
|
7
|
+
integrity="sha384-GSvmX7qIMnxd5kgPsLoA3YzwUaZQcKBmCh66PVPZNibhc4VRxD+6h61FyJd3/gD9"
|
|
8
8
|
crossorigin="anonymous" data-register></script>
|
|
9
9
|
```
|
|
10
10
|
|
package/dist/WebHotkeys.min.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
/*! WebHotkeys v1.1.
|
|
1
|
+
/*! WebHotkeys v1.1.1 | 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"],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,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?`
|
|
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){return!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 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=`
|
|
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;for(let
|
|
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);
|
package/package.json
CHANGED
package/src/WebHotkeys.js
CHANGED
|
@@ -57,6 +57,13 @@ const DEFAULT_STORAGE_KEY = "webhotkeys.remap"
|
|
|
57
57
|
const FORM_TAGS = ["INPUT", "SELECT", "TEXTAREA"]
|
|
58
58
|
/** 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
59
|
const NON_TEXT_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file", "range", "color"]
|
|
60
|
+
/**
|
|
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.
|
|
65
|
+
*/
|
|
66
|
+
const CONTROL_KEYS = { range: ["ArrowLeft", "ArrowRight", "Home", "End"] }
|
|
60
67
|
/** Input types a hotkey should activate instead of merely focusing (a range or a color still wants the focus - the arrows adjust it). */
|
|
61
68
|
const CLICKABLE_INPUT_TYPES = ["checkbox", "radio", "submit", "button", "reset", "image", "file"]
|
|
62
69
|
/** Is the element a text field, ie. would a letter key land in it? (A SELECT counts - letters do its typeahead.) */
|
|
@@ -1024,6 +1031,10 @@ class WebHotkeys {
|
|
|
1024
1031
|
* @returns {boolean}
|
|
1025
1032
|
*/
|
|
1026
1033
|
_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)
|
|
1037
|
+
}
|
|
1027
1038
|
return !e.altKey
|
|
1028
1039
|
&& !e.metaKey
|
|
1029
1040
|
&& (// this is a mere letter (not Escape, F1... which anticipate a hotkey)
|
|
@@ -1848,6 +1859,10 @@ class _Grid {
|
|
|
1848
1859
|
/**
|
|
1849
1860
|
* Locate the currently selected cell, its row and its column index. Falls back to the grid's
|
|
1850
1861
|
* very first cell when nothing currently matches `currentSelector`.
|
|
1862
|
+
*
|
|
1863
|
+
* With a `:focus` selector, a cell also counts when the focus sits on something inside it - a
|
|
1864
|
+
* checkbox or a slider in the cell. Otherwise an arrow pressed there would not know where it
|
|
1865
|
+
* is and jump to the very first cell.
|
|
1851
1866
|
* @returns {boolean} A cell (hence a position) has been found.
|
|
1852
1867
|
*/
|
|
1853
1868
|
_loadPosition() {
|
|
@@ -1855,10 +1870,11 @@ class _Grid {
|
|
|
1855
1870
|
if (!this.rows.length) {
|
|
1856
1871
|
return false
|
|
1857
1872
|
}
|
|
1873
|
+
const focusWithin = this.currentSelector.indexOf(":focus") === 0 && this._wh.activeElement()
|
|
1858
1874
|
for (let r = 0; r < this.rows.length; r++) {
|
|
1859
1875
|
const cells = this.rows[r].querySelectorAll(this.cellQuery)
|
|
1860
1876
|
for (let c = 0; c < cells.length; c++) {
|
|
1861
|
-
if (cells[c].matches(this.currentSelector)) {
|
|
1877
|
+
if (cells[c].matches(this.currentSelector) || (focusWithin && cells[c].contains?.(focusWithin))) {
|
|
1862
1878
|
this.rowIndex = r
|
|
1863
1879
|
this.colIndex = c
|
|
1864
1880
|
this.selected = cells[c]
|