webhotkeys 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +165 -0
- package/README.md +76 -0
- package/dist/WebHotkeys.min.js +34 -0
- package/package.json +59 -0
- package/src/WebHotkeys.js +2047 -0
- package/src/WebHotkeys.mjs +9 -0
- package/src/index.d.ts +222 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# WebHotkeys
|
|
2
|
+
|
|
3
|
+
Easy solution to integrate keyboard hotkeys into the webpage.
|
|
4
|
+
|
|
5
|
+
```html
|
|
6
|
+
<script src="https://cdn.jsdelivr.net/npm/webhotkeys@1.0.0/dist/WebHotkeys.min.js"
|
|
7
|
+
integrity="sha384-kli6SNUr+ie1vBdmK+/dF6zqPqcLhDdExJ7TtygxgYK4e+GNBUBJImI1zqNXBBrU"
|
|
8
|
+
crossorigin="anonymous" data-register></script>
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Keep the `crossorigin="anonymous"` attribute – without it the browser refuses to verify the [integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) hash and the script does not load at all. The hash belongs to that exact version, so copy the whole snippet as it is; a version bumped without the matching hash means the script silently stops loading.
|
|
12
|
+
|
|
13
|
+
While debugging, swap `dist/WebHotkeys.min.js` for `src/WebHotkeys.js` to get the readable source. It is a different file, hence a different hash – recompute it (`openssl dgst -sha384 -binary src/WebHotkeys.js | openssl base64 -A`) or leave the `integrity` attribute out of your local build.
|
|
14
|
+
|
|
15
|
+
Or install it from npm:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install webhotkeys
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```javascript
|
|
22
|
+
import WebHotkeys from "webhotkeys" // or: const WebHotkeys = require("webhotkeys")
|
|
23
|
+
const wh = new WebHotkeys()
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Both ESM (`import`) and CommonJS (`require`) work and TypeScript definitions are bundled. Note the npm/bundler build does not auto-register on `window.webHotkeys` (there is no `data-register` attribute there) - create the instance yourself as shown above.
|
|
27
|
+
|
|
28
|
+
## Examples
|
|
29
|
+
|
|
30
|
+
A tour through what the library can do. Each line is standalone, copy what you need.
|
|
31
|
+
|
|
32
|
+
```javascript
|
|
33
|
+
const wh = window.webHotkeys // or: const wh = new WebHotkeys()
|
|
34
|
+
|
|
35
|
+
// Plain combinations. The last parameter is optional in every `grab` call.
|
|
36
|
+
wh.grab("Alt+s", "Save the form", () => form.submit())
|
|
37
|
+
wh.grab("?", "Show the help", () => wh.toggleHelp(true)) // no need to mention Shift for a symbol
|
|
38
|
+
wh.grab("Mod+k", "Search", openSearch) // Ctrl+k, but Cmd+k on a Mac
|
|
39
|
+
|
|
40
|
+
// A sequence, GitHub style: hit `g`, then `i`.
|
|
41
|
+
wh.grab("g i", "Go to issues", () => location.assign("/issues"))
|
|
42
|
+
|
|
43
|
+
// An element instead of a callback - it gets clicked (or focused, if it is a form field).
|
|
44
|
+
wh.grab("Alt+n", "Focus the note", "#note")
|
|
45
|
+
|
|
46
|
+
// Groups: enable or disable a whole screen worth of hotkeys at once.
|
|
47
|
+
const editing = wh.group("Editing", [
|
|
48
|
+
["Ctrl+b", "Bold", () => exec("bold")],
|
|
49
|
+
["Ctrl+i", "Italics", () => exec("italic")],
|
|
50
|
+
])
|
|
51
|
+
editing.disable()
|
|
52
|
+
|
|
53
|
+
// Housekeeping.
|
|
54
|
+
wh.toggleHints(true) // badge every element having a hotkey, the Vimium way
|
|
55
|
+
wh.destroy() // detach everything (SPA unmount)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Declaratively, without touching JavaScript at all:
|
|
59
|
+
|
|
60
|
+
```html
|
|
61
|
+
<div data-hotkey-group="Navigation">
|
|
62
|
+
<a href="/inbox" data-hotkey="g i" title="Go to the inbox">Inbox</a>
|
|
63
|
+
<button data-hotkey="Alt+n" title="New message">New</button>
|
|
64
|
+
</div>
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
See the live [example](https://cz-nic.github.io/webhotkeys/example.html).
|
|
68
|
+
|
|
69
|
+
## Documentation
|
|
70
|
+
|
|
71
|
+
Full API reference, options, keyboard layouts and migration notes:
|
|
72
|
+
**[cz-nic.github.io/webhotkeys](https://cz-nic.github.io/webhotkeys/)**
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
LGPL-3.0-or-later
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/*! WebHotkeys v1.0.0 | LGPL-3.0-or-later | https://github.com/CZ-NIC/webhotkeys#readme
|
|
2
|
+
* Usage: <script src="WebHotkeys.min.js" data-register></script> then window.webHotkeys.grab("f", "Hint", fn)
|
|
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=h=>r&&h.includes(r)?h.replace(r,n):h+n;i.hint==="title"?t.title=l(t.title||""):i.hint==="text"&&(FORM_TAGS.includes(t.tagName)?t.labels?.[0]?.innerHTML&&(t.labels[0].innerHTML=l(t.labels[0].innerHTML)):t.innerHTML=l(t.innerHTML)),t.dataset.webhotkeysDisplayed=s}get clue(){return this.sequence.map(e=>Hotkey.comboText(e,this.wh?.isMac())).join(" ")}get combination(){return this.sequence.map(e=>Hotkey.comboText(e,!1)).join(" ")}get text(){return this.hint?`${this.clue}: ${this.hint}`:this.clue}static comboText(e,t=!1){const i=(e.key||e.code||"").replace(/^Digit(\d)$/,"$1");if(MODIFIER_KEYS.includes(i))return t?MAC_SYMBOLS[i==="Control"?"ctrl":i.toLowerCase()]:i;const s=["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]);if(t)return["ctrl","alt","shift","meta"].filter(r=>e[r+"Key"]).map(r=>MAC_SYMBOLS[r]).join("")+i;const n={ctrl:"Ctrl+",shift:"Shift+",alt:"Alt+",meta:"Meta+"};return["ctrl","shift","alt","meta"].filter(r=>s.includes(r)).map(r=>n[r]).join("")+i}static fromEvent(e){return MODIFIER_KEYS.includes(e.key)?e.key:Hotkey.comboText({...pickModifiers(e),[e.key?.length===1?"key":"code"]:e.key?.length===1?e.key:e.code})}get key_state(){return(this.event.key||this.event.code)+Hotkey.mod_state(this.event)}get registry(){return this.wh._hotkeys[this.key_state]||=[]}static mod_state(e,t=!1){return String((t?0:e.shiftKey<<3)|e.altKey<<2|e.ctrlKey<<1|e.metaKey)}static match(e,t){if(e.code&&e.code!==t.code&&CODE_ALIASES[t.code]!==e.code||e.key&&!keyEquals(e.key,t.key))return!1;const i=t.key?.length===1;return Hotkey.mod_state(e,i&&!/[A-Za-z]/.test(t.key))===Hotkey.mod_state(t,i&&!/[A-Za-z]/.test(t.key))}static isPrefixOf(e,t){return e.length<t.length&&e.every((i,s)=>Hotkey.match(i,t[s]))}rebind(e=null,t=!0){const i=this.enabled,s=this.clue;if(this.disable(),this.sequence=this.wh._parseSequence(e||this.defaultCombination),this.event=this.sequence[this.sequence.length-1],this._hintElement(s),i&&this.enable(),t){const n=this.combination;n===this.defaultCombination?delete this.wh._remap[this.defaultCombination]:this.wh._remap[this.defaultCombination]=n,this.wh._saveRemapping()}return this}_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}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(h=>e.has(h));return l.forEach(h=>t.add(h)),{name:n,hotkeys:l}}).filter(n=>n.hotkeys.length),s=Array.from(e).filter(n=>!t.has(n));return[...s.length?[{name:"",hotkeys:s}]:[],...i]}getText(){return this.getGroups().map(({name:e,hotkeys:t})=>(e?`
|
|
5
|
+
**${e}**
|
|
6
|
+
`:"")+t.map(i=>i.text).join(`
|
|
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=`
|
|
9
|
+
.webhotkeys-dialog { border: 0; border-radius: .5em; padding: 0; max-width: 40em; width: 90%; max-height: 80vh;
|
|
10
|
+
box-shadow: 0 .5em 2em rgba(0,0,0,.35); font: inherit; background: Canvas; color: CanvasText; }
|
|
11
|
+
.webhotkeys-dialog::backdrop { background: rgba(0,0,0,.4); }
|
|
12
|
+
.webhotkeys-head { display: flex; gap: .5em; align-items: center; padding: .75em 1em; border-bottom: 1px solid rgba(128,128,128,.3); }
|
|
13
|
+
.webhotkeys-head strong { flex: 0 0 auto; }
|
|
14
|
+
.webhotkeys-filter { flex: 1 1 auto; min-width: 4em; padding: .25em .5em; font: inherit; }
|
|
15
|
+
.webhotkeys-close { flex: 0 0 auto; cursor: pointer; border: 0; background: transparent; font: inherit; }
|
|
16
|
+
.webhotkeys-body { padding: .5em 1em 1em; overflow: auto; max-height: 65vh; }
|
|
17
|
+
.webhotkeys-body h3 { margin: 1em 0 .25em; font-size: 1em; opacity: .7; }
|
|
18
|
+
.webhotkeys-row { display: flex; gap: .75em; padding: .15em 0; }
|
|
19
|
+
.webhotkeys-key { flex: 0 0 9em; text-align: right; }
|
|
20
|
+
kbd.webhotkeys-key, button.webhotkeys-key { display: inline-block; font-family: monospace; font-size: .85em;
|
|
21
|
+
padding: .15em .5em; border: 1px solid rgba(128,128,128,.4); border-radius: .3em; background: rgba(128,128,128,.12); }
|
|
22
|
+
/* The remappable combination is a <button>; it must still read as the plain kbd badge above. */
|
|
23
|
+
button.webhotkeys-key { color: inherit; cursor: pointer; }
|
|
24
|
+
button.webhotkeys-key:hover { background: rgba(128,128,128,.22); }
|
|
25
|
+
button.webhotkeys-key:focus { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
26
|
+
.webhotkeys-recording { background: #ffd76e; color: #222; }
|
|
27
|
+
.webhotkeys-hint { flex: 1 1 auto; }
|
|
28
|
+
.webhotkeys-clash .webhotkeys-key { color: #c0392b; }
|
|
29
|
+
.webhotkeys-reset { flex: 0 0 auto; border: 0; background: transparent; color: inherit; cursor: pointer; opacity: .6; }
|
|
30
|
+
.webhotkeys-note { margin: 1.5em 0 0; font-style: italic; font-size: .9em; opacity: .6; }
|
|
31
|
+
.webhotkeys-hints { position: absolute; inset: 0; pointer-events: none; z-index: 2147483000; }
|
|
32
|
+
.webhotkeys-badge { position: absolute; transform: translate(-30%, -50%); pointer-events: none;
|
|
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:h,upDown:a=!1,homeEnd:c=!1,typeahead:f=!1}={}){e!==void 0&&(this.query=e),t!==void 0&&(this.currentSelector=t,i&&this._wh._insertCss(this.query+this.currentSelector+i)),s!==void 0&&(this.wrap=s),n!==void 0&&(this.scroll=n),r!==void 0&&(this.onChange=r),l!==void 0&&(this.onChanged=l),h!==void 0&&(this.scope=h),a&&this._handleUpDown(),c&&this._handleHomeEnd(),f&&this._handleTypeahead(typeof f=="number"?f:800)}_handleUpDown(){this._hotkeys.push(this._wh.grab("ArrowUp","Lists up",()=>this.goPrev(),this.scope),this._wh.grab("ArrowDown","Lists down",()=>this.goNext(),this.scope))}_handleHomeEnd(){this._hotkeys.push(this._wh.grab("Home","Lists first",()=>this.goFirst(),this.scope),this._wh.grab("End","Lists last",()=>this.goLast(),this.scope))}_handleTypeahead(e=800){let t="",i=0;this._typeahead=s=>{if(s.key?.length!==1||s.ctrlKey||s.altKey||s.metaKey||this._wh._isTextContext(s,this._wh.activeElement()))return;const n=Date.now();t=(n-i>e?"":t)+s.key.toLowerCase(),i=n,this.selectByPrefix(t)&&(s.preventDefault(),s.stopPropagation())},document.addEventListener("keydown",this._typeahead,!0)}selectByPrefix(e){this._loadSiblings();const t=Array.from(this.items||[]).find(i=>(i.innerText||i.textContent||"").trim().toLowerCase().startsWith(e));return t&&this._change(t,this.selected),!!t}destroy(){return this._typeahead&&(document.removeEventListener("keydown",this._typeahead,!0),this._typeahead=null),this._hotkeys.forEach(e=>e?.remove()),this._hotkeys=[],this}_loadSiblings(e=1){if(this.items=document.querySelectorAll(this.query),!this.items.length)return!1;for(let t of document.querySelectorAll(this.query))t.matches(this.currentSelector)&&(this.selected=t);if(this.selected){const t=this.items.length;for(let i=0;i<t;i++)if(this.selected.isSameNode(this.items[i]))return this.prev=this.items[this.wrap?_wrapIndex(i,-e,t):_clampIndex(i,-e,t)],this.next=this.items[this.wrap?_wrapIndex(i,e,t):_clampIndex(i,e,t)],!0}else return this.prev=this.next=this.selected=this.items[0],!0;return!1}get current(){return this._loadSiblings(),this.selected}set current(e){this._loadSiblings()&&(this._change(e),this._loadSiblings()||console.error("WebHotkeys.js> Could not change successfully to:",e))}goNext(e){return this._loadSiblings(e)?this._change(this.next,this.selected):!1}goPrev(e){return this._loadSiblings(e)?this._change(this.prev,this.selected):!1}goFirst(){return this._loadSiblings()?this._change(this.items[0],this.selected):!1}goLast(){return this._loadSiblings()?this._change(this.items[this.items.length-1],this.selected):!1}go(e=!0,t=1){return this._loadSiblings(t)?this._change(e?this.next:this.prev,this.selected):!1}_change(e,t){return _applyChange(this,e,t)}}class _Grid{constructor(e,t,i,{current:s=":focus",wrap:n=!1,scroll:r=!0,onChange:l=null,onChanged:h=null,scope:a=null}={}){this._wh=e,this.rowQuery=t,this.cellQuery=i,this.currentSelector=s,this.wrap=n,this.scroll=r,this.onChange=l,this.onChanged=h,this.selected=null,this._hotkeys=[this._wh.grab("ArrowUp","Grid up",()=>this.go(-1,0),a),this._wh.grab("ArrowDown","Grid down",()=>this.go(1,0),a),this._wh.grab("ArrowLeft","Grid left",()=>this.go(0,-1),a),this._wh.grab("ArrowRight","Grid right",()=>this.go(0,1),a)]}_loadPosition(){if(this.rows=Array.from(document.querySelectorAll(this.rowQuery)),!this.rows.length)return!1;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
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "webhotkeys",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Easy solution to integrate keyboard hotkeys into the webpage.",
|
|
5
|
+
"main": "src/WebHotkeys.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"src/",
|
|
8
|
+
"dist/"
|
|
9
|
+
],
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/CZ-NIC/webhotkeys.git"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"hotkeys",
|
|
16
|
+
"keyboard",
|
|
17
|
+
"shortcuts",
|
|
18
|
+
"accesskey",
|
|
19
|
+
"keybindings",
|
|
20
|
+
"key-sequence",
|
|
21
|
+
"vanilla-js"
|
|
22
|
+
],
|
|
23
|
+
"author": "Edvard Rejthar",
|
|
24
|
+
"license": "LGPL-3.0-or-later",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/CZ-NIC/webhotkeys/issues"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/CZ-NIC/webhotkeys#readme",
|
|
29
|
+
"module": "src/WebHotkeys.mjs",
|
|
30
|
+
"types": "src/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./src/index.d.ts",
|
|
34
|
+
"import": "./src/WebHotkeys.mjs",
|
|
35
|
+
"require": "./src/WebHotkeys.js",
|
|
36
|
+
"default": "./src/WebHotkeys.js"
|
|
37
|
+
},
|
|
38
|
+
"./WebHotkeys.js": "./src/WebHotkeys.js",
|
|
39
|
+
"./WebHotkeys.min.js": "./dist/WebHotkeys.min.js",
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"sideEffects": false,
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "for f in test/*.test.js; do node \"$f\" || exit 1; done; node test/esm-import.test.mjs",
|
|
45
|
+
"test:min": "WH_FILE=dist/WebHotkeys.min.js npm test",
|
|
46
|
+
"build": "node scripts/build.js",
|
|
47
|
+
"lint": "eslint .",
|
|
48
|
+
"preversion": "npm run lint && npm test",
|
|
49
|
+
"version": "npm run build && node scripts/stamp-changelog.js && npm run test:min && git add README.md CHANGELOG.md",
|
|
50
|
+
"postversion": "git push --follow-tags",
|
|
51
|
+
"release": "node scripts/release.js",
|
|
52
|
+
"prepack": "npm run build && npm run test:min"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"esbuild": "0.28.2",
|
|
56
|
+
"eslint": "^10.9.0",
|
|
57
|
+
"globals": "^17.11.0"
|
|
58
|
+
}
|
|
59
|
+
}
|