webhotkeys 1.0.0 → 1.1.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 +2 -2
- package/dist/WebHotkeys.min.js +4 -4
- package/package.json +1 -1
- package/src/WebHotkeys.js +85 -13
- package/src/index.d.ts +13 -2
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.
|
|
7
|
-
integrity="sha384-
|
|
6
|
+
<script src="https://cdn.jsdelivr.net/npm/webhotkeys@1.1.0/dist/WebHotkeys.min.js"
|
|
7
|
+
integrity="sha384-b/MTmeymj5zGJ0VKv0EJK1hSNdlPyxRNRniqSp97iYYbsIjyNeCSrRVYLFMIE8cL"
|
|
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
|
+
/*! WebHotkeys v1.1.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,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.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=
|
|
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?`
|
|
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;s&&typeof s=="object"&&Object.getPrototypeOf(Object.getPrototypeOf(s)??{})===null&&(n=s.inInput??!1,r=s.group??null,s=s.scope??null);let l=!e||!i;if(isString(i))try{i=document.querySelector(i)}catch{l=!0}if(l){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;const a=this._remap[h.defaultCombination];a&&a!==h.combination&&h.rebind(a,!1);const{element:c}=h,{groupAttribute:f}=this.options;if(c){this._dom.set(c,h);const p=c.closest(`[${f}]`)?.getAttribute(f);p&&this.group(p).push(h)}if(r&&this.group(r).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 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.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))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(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=`
|
|
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=`
|
|
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:
|
|
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 t=0;t<this.rows.length;t++){const i=this.rows[t].querySelectorAll(this.cellQuery);for(let s=0;s<i.length;s++)if(i[s].matches(this.currentSelector))return this.rowIndex=t,this.colIndex=s,this.selected=i[s],!0}const e=this.rows[0].querySelectorAll(this.cellQuery);return e.length?(this.rowIndex=0,this.colIndex=0,this.selected=e[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
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* @property {string} [attribute='data-hotkey'] Attribute name to link DOM elements to shorcuts.
|
|
15
15
|
* @property {string} [groupAttribute='data-hotkey-group'] Attribute name to link DOM elements to shorcut groups.
|
|
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
|
+
* @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
|
|
17
18
|
* @property {?string|?function} [ignore=null] Selector or callback(activeElement, event). When it matches, no hotkey is triggered at all.
|
|
18
19
|
* @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.
|
|
19
20
|
* @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.
|
|
@@ -26,7 +27,7 @@ const WebHotkeysDefaults = {
|
|
|
26
27
|
replaceAccesskeys: true, helpKey: "F1", help: "dialog", hintKey: "F2",
|
|
27
28
|
attribute: "data-hotkey", groupAttribute: "data-hotkey-group", actionAttribute: "data-hotkey-action",
|
|
28
29
|
observe: true, onToggle: null, onTrigger: null, onMiss: null, hint: "title",
|
|
29
|
-
ignore: null, sequenceTimeout: 1000, mac: null, warnConflicts: false,
|
|
30
|
+
ignore: null, sequenceTimeout: 1000, mac: null, warnConflicts: false, inHidden: false,
|
|
30
31
|
remap: true, onRemap: null
|
|
31
32
|
}
|
|
32
33
|
|
|
@@ -119,6 +120,12 @@ class Hotkey {
|
|
|
119
120
|
this.wh = wh
|
|
120
121
|
/** @type {boolean} Fire even when the user is typing into an input. @see allowInput */
|
|
121
122
|
this.allowInput = false
|
|
123
|
+
/** @type {?boolean} Fire even when the linked element is hidden. Null inherits the `inHidden` option. */
|
|
124
|
+
this.allowHidden = null
|
|
125
|
+
/** @type {?string} The modifier the hotkey currently sits behind. @see displace */
|
|
126
|
+
this._displaced = null
|
|
127
|
+
/** @type {?KeyEvent[]} Where a displaced hotkey returns to. */
|
|
128
|
+
this._base = null
|
|
122
129
|
/** @type {string} The combination the hotkey was grabbed with. Survives `rebind`, hence remapping. */
|
|
123
130
|
this.defaultCombination = this.combination
|
|
124
131
|
/** @type {?HTMLElement} The hotkey is linked to this DOM element. */
|
|
@@ -282,15 +289,11 @@ class Hotkey {
|
|
|
282
289
|
* @returns {Hotkey}
|
|
283
290
|
*/
|
|
284
291
|
rebind(combination = null, store = true) {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
this.
|
|
288
|
-
this.
|
|
289
|
-
this.
|
|
290
|
-
this._hintElement(previousClue)
|
|
291
|
-
if (was) {
|
|
292
|
-
this.enable()
|
|
293
|
-
}
|
|
292
|
+
// Relocating the hotkey outright ends any displacement; the new place becomes the base
|
|
293
|
+
// a following `displace` puts its modifier on.
|
|
294
|
+
this._displaced = null
|
|
295
|
+
this._base = null
|
|
296
|
+
this._applySequence(this.wh._parseSequence(combination || this.defaultCombination))
|
|
294
297
|
if (store) {
|
|
295
298
|
const current = this.combination
|
|
296
299
|
if (current === this.defaultCombination) {
|
|
@@ -303,6 +306,63 @@ class Hotkey {
|
|
|
303
306
|
return this
|
|
304
307
|
}
|
|
305
308
|
|
|
309
|
+
/**
|
|
310
|
+
* Put the hotkey on another sequence, keeping the enabled state and the element hint in sync.
|
|
311
|
+
* The sequence is already parsed - unlike a combination string, it never loses the `Digit1` /
|
|
312
|
+
* `1` distinction, which matters when a displaced hotkey has to coexist with its bare key.
|
|
313
|
+
* @param {KeyEvent[]} sequence
|
|
314
|
+
*/
|
|
315
|
+
_applySequence(sequence) {
|
|
316
|
+
const was = this.enabled
|
|
317
|
+
const previousClue = this.clue
|
|
318
|
+
this.disable()
|
|
319
|
+
this.sequence = sequence
|
|
320
|
+
this.event = sequence[sequence.length - 1]
|
|
321
|
+
this._hintElement(previousClue)
|
|
322
|
+
if (was) {
|
|
323
|
+
this.enable()
|
|
324
|
+
}
|
|
325
|
+
return this
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Move the hotkey behind a modifier for as long as something else needs its bare combination,
|
|
330
|
+
* ex. a mode of the application took the digits over. Unlike `rebind`, this is the program's
|
|
331
|
+
* doing, not the user's: it never enters the remapping and `displace(null)` puts the hotkey back
|
|
332
|
+
* to wherever it sat before (the user's remapped combination, or the default).
|
|
333
|
+
* Only the first combination of a sequence is prefixed - that is the one clashing.
|
|
334
|
+
* A hotkey already holding the modifier stays where it is.
|
|
335
|
+
* @param {?Key} modifier 'Shift', 'Alt', 'Ctrl', 'Meta' or 'Mod'. Nothing (or null) puts the hotkey back.
|
|
336
|
+
* @returns {Hotkey}
|
|
337
|
+
*/
|
|
338
|
+
displace(modifier = null) {
|
|
339
|
+
modifier = modifier || null
|
|
340
|
+
if (this._displaced === modifier) {
|
|
341
|
+
return this
|
|
342
|
+
}
|
|
343
|
+
if (!modifier) {
|
|
344
|
+
const base = this._base
|
|
345
|
+
this._displaced = null
|
|
346
|
+
this._base = null
|
|
347
|
+
return base ? this._applySequence(base) : this
|
|
348
|
+
}
|
|
349
|
+
// Resolved through the aliases - 'Ctrl'/'Control', or 'Mod' (Meta on a Mac, Control elsewhere).
|
|
350
|
+
let name = MODIFIER_ALIASES[String(modifier).toLowerCase()]
|
|
351
|
+
if (name === "Mod") {
|
|
352
|
+
name = this.wh.isMac() ? "Meta" : "Control"
|
|
353
|
+
}
|
|
354
|
+
const flag = { Shift: "shiftKey", Alt: "altKey", Control: "ctrlKey", Meta: "metaKey" }[name]
|
|
355
|
+
if (!flag) {
|
|
356
|
+
console.warn(`WebHotkeys.js> displace: '${modifier}' is not a modifier`)
|
|
357
|
+
return this
|
|
358
|
+
}
|
|
359
|
+
const base = this._base ||= this.sequence // where to return to; captured before the first move
|
|
360
|
+
this._displaced = modifier
|
|
361
|
+
// A combination already holding the modifier has nothing to free - prefixing it would only
|
|
362
|
+
// collide with whatever legitimately sits on the doubled combination.
|
|
363
|
+
return base[0][flag] ? this : this._applySequence([{ ...base[0], [flag]: true }, ...base.slice(1)])
|
|
364
|
+
}
|
|
365
|
+
|
|
306
366
|
_enable() {
|
|
307
367
|
if (!this.registry.includes(this)) {
|
|
308
368
|
this.registry.unshift(this)
|
|
@@ -375,6 +435,14 @@ class HotkeyGroup extends Array {
|
|
|
375
435
|
this.forEach(hotkey => hotkey.toggle(enable))
|
|
376
436
|
return this
|
|
377
437
|
}
|
|
438
|
+
/**
|
|
439
|
+
* Move every hotkey of the group behind a modifier (`null` puts them back). @see Hotkey.displace
|
|
440
|
+
* @param {?Key} modifier
|
|
441
|
+
*/
|
|
442
|
+
displace(modifier = null) {
|
|
443
|
+
this.forEach(hotkey => hotkey.displace(modifier))
|
|
444
|
+
return this
|
|
445
|
+
}
|
|
378
446
|
/** Forget all the hotkeys of the group. @see Hotkey.remove */
|
|
379
447
|
remove() {
|
|
380
448
|
this.slice().forEach(hotkey => hotkey.remove())
|
|
@@ -611,25 +679,28 @@ class WebHotkeys {
|
|
|
611
679
|
* @param {Action} action What will happen on hotkey trigger.
|
|
612
680
|
* If action returns false, hotkey will be treated as non-existent and event will propagate further.
|
|
613
681
|
* If action is a HTMLElement or its string selector, its click or focus method (form elements) is invoked instead.
|
|
614
|
-
* @param {?Action|{scope: ?Action, inInput: ?boolean, group: ?string}} scope Scope within the hotkey is allowed to be launched,
|
|
615
|
-
* or an options object `{scope, inInput, group}`.
|
|
682
|
+
* @param {?Action|{scope: ?Action, inInput: ?boolean, inHidden: ?boolean, group: ?string}} scope Scope within the hotkey is allowed to be launched,
|
|
683
|
+
* or an options object `{scope, inInput, inHidden, group}`.
|
|
616
684
|
* The scope can be an HTMLElement that the active element is being search under when the hotkey triggers.
|
|
617
685
|
* The scope can an HTMLElement selector, does not have to exist at the shorcut definition time.
|
|
618
686
|
* The scope can be a function, resolved at the keystroke time. True means the scope matches. That way, you can implement negative scope.
|
|
619
687
|
* (Ex: down arrow should work unless there is DialogOverlay in the document root.)
|
|
620
688
|
* `inInput: true` fires the hotkey even while the user is typing into an input or a contenteditable
|
|
621
689
|
* (ex: arrow keys navigating a combobox's suggestion list). @see Hotkey.allowInput
|
|
690
|
+
* `inHidden` overrides the `inHidden` option for this single hotkey. @see Hotkey.allowHidden
|
|
622
691
|
* `group` adds the hotkey to a named `HotkeyGroup` (same as `wh.group(name, [[...]])` would).
|
|
623
692
|
* @returns {Hotkey}
|
|
624
693
|
*/
|
|
625
694
|
grab(hotkey, hint, action, scope = null) {
|
|
626
695
|
let inInput = false
|
|
696
|
+
let inHidden = null
|
|
627
697
|
let group = null
|
|
628
698
|
// An options object `{scope, inInput, group}`, not a plain scope. Checked by prototype chain depth,
|
|
629
699
|
// not `typeof` (an HTMLElement/selector-result is an object too) nor `=== Object.prototype`
|
|
630
700
|
// (breaks across realms, ex: a test running WebHotkeys.js inside a `vm` context).
|
|
631
701
|
if (scope && typeof scope === "object" && Object.getPrototypeOf(Object.getPrototypeOf(scope) ?? {}) === null) {
|
|
632
702
|
inInput = scope.inInput ?? false
|
|
703
|
+
inHidden = scope.inHidden ?? null
|
|
633
704
|
group = scope.group ?? null
|
|
634
705
|
scope = scope.scope ?? null
|
|
635
706
|
}
|
|
@@ -648,6 +719,7 @@ class WebHotkeys {
|
|
|
648
719
|
// register hotkey and set the hint to the DOM
|
|
649
720
|
const hotkeyO = new Hotkey(action, hint, scope, this._parseSequence(hotkey), this)
|
|
650
721
|
hotkeyO.allowInput = inInput
|
|
722
|
+
hotkeyO.allowHidden = inHidden
|
|
651
723
|
|
|
652
724
|
// The user may have remapped this very combination in a previous session (or in another
|
|
653
725
|
// view that has been unmounted since) – honour it right away, before anyone sees the hint.
|
|
@@ -1095,7 +1167,7 @@ class WebHotkeys {
|
|
|
1095
1167
|
|
|
1096
1168
|
let result
|
|
1097
1169
|
if (element) {
|
|
1098
|
-
if (element.disabled || !isVisible(element)) {
|
|
1170
|
+
if (element.disabled || (!isVisible(element) && !(hotkey.allowHidden ?? this.options.inHidden))) {
|
|
1099
1171
|
return false // action is a disabled or hidden HTMLElement, try next shorcut
|
|
1100
1172
|
}
|
|
1101
1173
|
// note that result is always none
|
package/src/index.d.ts
CHANGED
|
@@ -54,6 +54,10 @@ export interface WebHotkeysOptions {
|
|
|
54
54
|
mac?: boolean | null
|
|
55
55
|
/** Warn in the console when a newly grabbed hotkey shadows a scope-less one. */
|
|
56
56
|
warnConflicts?: boolean
|
|
57
|
+
/** Let a hotkey fire even when its linked element is hidden. The default skips it, so a hidden
|
|
58
|
+
* panel does not swallow the combination; set it when the elements are mere affordances of the
|
|
59
|
+
* hotkeys (a fading toolbar). Overridable per hotkey. @default false */
|
|
60
|
+
inHidden?: boolean
|
|
57
61
|
}
|
|
58
62
|
|
|
59
63
|
export declare class Hotkey {
|
|
@@ -68,6 +72,8 @@ export declare class Hotkey {
|
|
|
68
72
|
enabled: boolean
|
|
69
73
|
/** Fires even while the user is typing. Set via `grab(..., {inInput: true})`, or directly. */
|
|
70
74
|
allowInput: boolean
|
|
75
|
+
/** Fires even while the linked element is hidden. Null inherits the `inHidden` option. */
|
|
76
|
+
allowHidden: boolean | null
|
|
71
77
|
/** The combination the hotkey was grabbed with; survives `rebind`. */
|
|
72
78
|
defaultCombination: Key
|
|
73
79
|
|
|
@@ -79,6 +85,9 @@ export declare class Hotkey {
|
|
|
79
85
|
readonly text: string
|
|
80
86
|
/** Move the hotkey to another combination (user remapping). No argument = back to the default. */
|
|
81
87
|
rebind(combination?: Key | null): this
|
|
88
|
+
/** Temporarily put the hotkey behind a modifier ("Shift", "Alt", "Ctrl", "Meta", "Mod"), ex. while
|
|
89
|
+
* a mode of the application needs its bare key. No argument = back where it sat. Not a remapping. */
|
|
90
|
+
displace(modifier?: Key | null): this
|
|
82
91
|
enable(): this
|
|
83
92
|
disable(): this
|
|
84
93
|
toggle(enable?: boolean | null): this
|
|
@@ -94,6 +103,8 @@ export declare class HotkeyGroup extends Array<Hotkey> {
|
|
|
94
103
|
enable(): this
|
|
95
104
|
disable(): this
|
|
96
105
|
toggle(enable?: boolean | null): this
|
|
106
|
+
/** Put every hotkey of the group behind a modifier (no argument = back). @see Hotkey.displace */
|
|
107
|
+
displace(modifier?: Key | null): this
|
|
97
108
|
remove(): this
|
|
98
109
|
}
|
|
99
110
|
|
|
@@ -165,8 +176,8 @@ export declare class WebHotkeys {
|
|
|
165
176
|
/** Detach the listener and the observer, forget every hotkey. */
|
|
166
177
|
destroy(): this
|
|
167
178
|
|
|
168
|
-
grab(hotkey: Key, hint: string, action: Action, scope?: Scope | { scope?: Scope | null, inInput?: boolean, group?: string | null } | null): Hotkey
|
|
169
|
-
group(name: string, definitions?: Array<[Key, string, Action, (Scope | { scope?: Scope | null, inInput?: boolean, group?: string | null } | null)?]>): HotkeyGroup
|
|
179
|
+
grab(hotkey: Key, hint: string, action: Action, scope?: Scope | { scope?: Scope | null, inInput?: boolean, inHidden?: boolean, group?: string | null } | null): Hotkey
|
|
180
|
+
group(name: string, definitions?: Array<[Key, string, Action, (Scope | { scope?: Scope | null, inInput?: boolean, inHidden?: boolean, group?: string | null } | null)?]>): HotkeyGroup
|
|
170
181
|
/** Every call returns its own independent instance, so several lists can coexist on one page. */
|
|
171
182
|
list(query?: string, options?: ListOptions): HotkeyList
|
|
172
183
|
/** 2D keyboard navigation over a table (rows × cells within a row). Every call returns its own
|