@ramstack/alpinegear-hotkey 1.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # @ramstack/alpinegear-hotkey
2
+
3
+ `@ramstack/alpinegear-hotkey` is a plugin for [Alpine.js](https://alpinejs.dev/) that provides the `x-hotkey` directive.
4
+
5
+ This directive allows you to easily handle keyboard shortcuts within your Alpine.js components or application.
6
+
7
+ Uses [@ramstack/hotkey](https://github.com/rameel/ramstack.hotkey.js) package under the hood.
8
+
9
+ ## Installation
10
+
11
+ ### Using CDN
12
+ To include the CDN version of this plugin, add the following `<script>` tag before the core `alpine.js` file:
13
+
14
+ ```html
15
+ <!-- alpine.js plugin -->
16
+ <script src="https://cdn.jsdelivr.net/npm/@ramstack/alpinegear-hotkey@1/alpinegear-hotkey.min.js" defer></script>
17
+
18
+ <!-- alpine.js -->
19
+ <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
20
+ ```
21
+
22
+ ### Using NPM
23
+ Alternatively, you can install the plugin via `npm`:
24
+
25
+ ```bash
26
+ npm install --save @ramstack/alpinegear-hotkey
27
+ ```
28
+
29
+ Then initialize it in your bundle:
30
+
31
+ ```js
32
+ import Alpine from "alpinejs";
33
+ import hotkey from "@ramstack/alpinegear-hotkey";
34
+
35
+ Alpine.plugin(hotkey);
36
+ Alpine.start();
37
+ ```
38
+
39
+ ## Usage
40
+ Define a hotkey combination using the directive by specifying key modifiers (such as `Ctrl`, `Alt`, `Shift`) with a `+` sign
41
+ (e.g., `Ctrl+Alt+Shift+S`).
42
+
43
+ Here's a simple example:
44
+
45
+ ```html
46
+ <div x-data x-hotkey.shift+f.window="console.log($event.hotkey)">
47
+ Hello, World!
48
+ </div>
49
+ ```
50
+
51
+ > [!TIP]
52
+ > The hotkey is **case-insensitive**. Standard key names are used.
53
+ >
54
+ > You can find a list of key names here [Key values for keyboard events](https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values)
55
+
56
+ ### Event Object
57
+
58
+ The `x-hotkey` directive provides access to the native JavaScript event object via the magic `$event` property.
59
+
60
+ ```html
61
+ <div x-data x-hotkey.shift+f.window="console.log($event)"></div>
62
+ ```
63
+
64
+ Also, the `x-hotkey` automatically passes the event object as the first argument to the method handler:
65
+
66
+ ```html
67
+ <div x-data x-hotkey.shift+f.window="e => console.log(e)"></div>
68
+
69
+ <!-- OR -->
70
+ <div x-data x-hotkey.shift+f.window="handle"></div>
71
+
72
+ <script>
73
+ function handle(e) {
74
+ console.log(e);
75
+ }
76
+ </script>
77
+ ```
78
+
79
+ ### Event Modifiers
80
+ To simplify common tasks like calling `event.preventDefault()` or `event.stopPropagation()`,
81
+ the `x-hotkey` directive supports following event modifiers:
82
+ * `.prevent` - calls `event.preventDefault()` before calling the event handler.
83
+ * `.stop` - call `event.stopPropagation()`, stopping the event from propagating further.
84
+ * `.passive` - indicates that the handler will never call `event.preventDefault()`, which improves scrolling performance for touch and wheel events.
85
+ * `.capture` - calling the event handler in the capture phase instead of the bubbling phase.
86
+ * `.once` - ensures the event handler is called only once.
87
+
88
+ ```html
89
+ <!-- prevent the default behavior for the keyboard event -->
90
+ <div x-hotkey.ctrl+s.prevent="save($event)"></div>
91
+
92
+ <!-- the event's propagation will be stopped -->
93
+ <div x-hotkey.ctrl+s.stop="save($event)"></div>
94
+
95
+ <!-- modifiers can be chained -->
96
+ <div x-hotkey.ctrl+s.prevent.stop="save($event)"></div>
97
+ ```
98
+
99
+ ### Global Event Listening
100
+ Use the `window` or `document` modifiers to listen for hotkeys globally, across the entire page:
101
+
102
+ ```html
103
+ <div x-hotkey.ctrl+s.window.prevent="save($event)"></div>
104
+ ```
105
+
106
+ ### Defining Alternative Hotkeys
107
+ You can assign multiple hotkeys to a single action by separating them with a dot (`.`).
108
+ For instance, in the example below, the same action is triggered by both `Ctrl + Shift + S` and `Alt + U`.
109
+
110
+ To determine which hotkey triggered the event, use the `hotkey` property from the event object.
111
+ This property contains the string representation of the hotkey.
112
+
113
+ ```html
114
+ <div x-data x-hotkey.ctrl+shift+f.alt+u.window="console.log($event.hotkey)">
115
+ Hello, World!
116
+ </div>
117
+ ```
118
+
119
+ ### Specific Events Listening
120
+ To change the event that `x-hotkey` listens for, use a directive argument.
121
+ By default, the event is `keydown`, but you can specify `keyup`, `keypress`, or others:
122
+
123
+ ```html
124
+ <div x-hotkey:keyup.alt+u="console.log('Search...')"></div>
125
+ ```
126
+
127
+ ### Exclude Elements
128
+
129
+ If you want to prevent hotkey handling from being triggered by specific elements, add the `data-hotkey-ignore` attribute to those elements:
130
+
131
+ ```html
132
+ <div x-hotkey.shift+k="...">
133
+ ...
134
+ <!-- Ignoring hotkeys from the input element -->
135
+ <input type="text" data-hotkey-ignore>
136
+ </div>
137
+ ```
138
+
139
+ You can also exclude a group of elements by applying the attribute to their parent:
140
+
141
+ ```html
142
+ <div x-hotkey.shift+k="...">
143
+ ...
144
+
145
+ <!-- Ignoring hotkeys from all elements within the form -->
146
+ <form data-hotkey-ignore>
147
+ ...
148
+ </form>
149
+ </div>
150
+ ```
151
+
152
+
153
+ ## Source code
154
+ You can find the source code for this plugin on GitHub:
155
+
156
+ https://github.com/rameel/ramstack.alpinegear.js/tree/main/src/plugins/hotkey
157
+
158
+ ## Contributions
159
+ Bug reports and contributions are welcome.
160
+
161
+ ## License
162
+ This package is released as open source under the **MIT License**.
163
+ See the [LICENSE](https://github.com/rameel/ramstack.alpinegear.js/blob/main/LICENSE) file for more details.
@@ -0,0 +1,140 @@
1
+ const aliases = {
2
+ "esc": "escape",
3
+ "ins": "insert",
4
+ "del": "delete",
5
+ "up": "arrowup",
6
+ "down": "arrowdown",
7
+ "right": "arrowright",
8
+ "left": "arrowleft",
9
+ "pgup": "pageup",
10
+ "pgdn": "pagedown",
11
+ "break": "pause",
12
+ "scroll": "scrolllock",
13
+ "scrlk": "scrolllock",
14
+ "prtscr": "printscreen",
15
+ "win": "meta",
16
+ "windows": "meta",
17
+ "cmd": "meta",
18
+ "command": "meta",
19
+ "comma": ",",
20
+ "period": ".",
21
+ "quote": "\"",
22
+ "singlequote": "'",
23
+ "colon": ":",
24
+ "semicolon": ";",
25
+ "plus": "+",
26
+ "minus": "-",
27
+ "tilde": "~",
28
+ "equal": "=",
29
+ "slash": "/"
30
+ };
31
+ const controlKeys = [
32
+ "ctrlKey",
33
+ "altKey",
34
+ "shiftKey",
35
+ "metaKey"
36
+ ];
37
+ function registerHotkey(target, hotkey, handler, eventName = "keydown", options) {
38
+ const info = describe(hotkey);
39
+ if (typeof target === "string") {
40
+ target = document.querySelector(target) ?? error(`No element found for selector '${target}'`);
41
+ }
42
+ return listen(target, eventName, function (e) {
43
+ if (!e.target?.closest("[data-hotkey-ignore]")) {
44
+ if (info.code === e.code.toUpperCase()) {
45
+ if (controlKeys.every(n => info[n] === e[n])) {
46
+ handler.call(this, e);
47
+ }
48
+ }
49
+ }
50
+ }, options);
51
+ }
52
+ function describe(hotkey) {
53
+ const keys = hotkey.replace(/\s+/g, "").toLowerCase().split("+");
54
+ const info = keys.reduce((data, k) => {
55
+ k = aliases[k] ?? k;
56
+ switch (k) {
57
+ case "ctrl":
58
+ case "alt":
59
+ case "shift":
60
+ case "meta":
61
+ data[`${k}Key`] = true;
62
+ break;
63
+ default:
64
+ k.length || invalidKey(hotkey);
65
+ k = k.toUpperCase();
66
+ data.code = k.length === 1 && k >= 'A' && k <= 'Z' ? `KEY${k}` : k;
67
+ break;
68
+ }
69
+ return data;
70
+ }, {
71
+ code: "",
72
+ ctrlKey: false,
73
+ altKey: false,
74
+ shiftKey: false,
75
+ metaKey: false
76
+ });
77
+ info.code || invalidKey(hotkey);
78
+ return info;
79
+ }
80
+ function listen(target, type, callback, options) {
81
+ target.addEventListener(type, callback, options);
82
+ return () => target.removeEventListener(type, callback, options);
83
+ }
84
+ function invalidKey(hotkey) {
85
+ error(`Invalid hotkey: '${hotkey}'`);
86
+ }
87
+ function error(message) {
88
+ throw new Error(message);
89
+ }
90
+
91
+ const has_modifier = (modifiers, modifier) => modifiers.includes(modifier);
92
+
93
+ const single = (...fns) => (...args) => {
94
+ for (const fn of fns) {
95
+ fn && fn(...args);
96
+ }
97
+ };
98
+
99
+ const option_keys = ["capture", "passive", "once", "prevent", "stop", "window", "document"];
100
+
101
+ function plugin({ directive }) {
102
+ directive("hotkey", (el, { expression, value, modifiers }, { evaluateLater, cleanup }) => {
103
+ const listener = e => evaluate(() => { }, { scope: { $event: e }, params: [e] });
104
+
105
+ const evaluate = expression
106
+ ? evaluateLater(expression)
107
+ : () => {};
108
+
109
+ const target =
110
+ has_modifier(modifiers, "window")
111
+ ? window
112
+ : has_modifier(modifiers, "document")
113
+ ? document
114
+ : el;
115
+
116
+ const disposes = modifiers
117
+ .filter(m => !option_keys.includes(m))
118
+ .flatMap(s => s.split(","))
119
+ .map(hotkey => registerHotkey(
120
+ target,
121
+ hotkey,
122
+ e => {
123
+ has_modifier(modifiers, "prevent") && e.preventDefault();
124
+ has_modifier(modifiers, "stop") && e.stopPropogation();
125
+
126
+ e.hotkey = hotkey;
127
+ listener(e);
128
+ },
129
+ value || "keydown",
130
+ {
131
+ capture: has_modifier(modifiers, "capture"),
132
+ passive: has_modifier(modifiers, "passive"),
133
+ once: has_modifier(modifiers, "once")
134
+ }));
135
+
136
+ cleanup(single(...disposes));
137
+ });
138
+ }
139
+
140
+ export { plugin as hotkey };
@@ -0,0 +1 @@
1
+ const e={esc:"escape",ins:"insert",del:"delete",up:"arrowup",down:"arrowdown",right:"arrowright",left:"arrowleft",pgup:"pageup",pgdn:"pagedown",break:"pause",scroll:"scrolllock",scrlk:"scrolllock",prtscr:"printscreen",win:"meta",windows:"meta",cmd:"meta",command:"meta",comma:",",period:".",quote:'"',singlequote:"'",colon:":",semicolon:";",plus:"+",minus:"-",tilde:"~",equal:"=",slash:"/"},t=["ctrlKey","altKey","shiftKey","metaKey"];function o(e){n(`Invalid hotkey: '${e}'`)}function n(e){throw new Error(e)}const r=(e,t)=>e.includes(t),c=["capture","passive","once","prevent","stop","window","document"];function s({directive:s}){s("hotkey",((s,{expression:a,value:l,modifiers:i},{evaluateLater:p,cleanup:u})=>{const d=a?p(a):()=>{},m=r(i,"window")?window:r(i,"document")?document:s;u(((...e)=>(...t)=>{for(const o of e)o&&o(...t)})(...i.filter((e=>!c.includes(e))).flatMap((e=>e.split(","))).map((c=>function(r,c,s,a="keydown",l){const i=function(t){const n=t.replace(/\s+/g,"").toLowerCase().split("+").reduce(((n,r)=>{switch(r=e[r]??r){case"ctrl":case"alt":case"shift":case"meta":n[`${r}Key`]=!0;break;default:r.length||o(t),r=r.toUpperCase(),n.code=1!==r.length||"A">r||r>"Z"?r:`KEY${r}`}return n}),{code:"",ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1});return n.code||o(t),n}(c);return"string"==typeof r&&(r=document.querySelector(r)??n(`No element found for selector '${r}'`)),function(e,t,o,n){return e.addEventListener(t,o,n),()=>e.removeEventListener(t,o,n)}(r,a,(function(e){e.target?.closest("[data-hotkey-ignore]")||i.code===e.code.toUpperCase()&&t.every((t=>i[t]===e[t]))&&s.call(this,e)}),l)}(m,c,(e=>{r(i,"prevent")&&e.preventDefault(),r(i,"stop")&&e.stopPropogation(),e.hotkey=c,(e=>{d((()=>{}),{scope:{$event:e},params:[e]})})(e)}),l||"keydown",{capture:r(i,"capture"),passive:r(i,"passive"),once:r(i,"once")})))))}))}export{s as hotkey};
@@ -0,0 +1,145 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ const aliases = {
5
+ "esc": "escape",
6
+ "ins": "insert",
7
+ "del": "delete",
8
+ "up": "arrowup",
9
+ "down": "arrowdown",
10
+ "right": "arrowright",
11
+ "left": "arrowleft",
12
+ "pgup": "pageup",
13
+ "pgdn": "pagedown",
14
+ "break": "pause",
15
+ "scroll": "scrolllock",
16
+ "scrlk": "scrolllock",
17
+ "prtscr": "printscreen",
18
+ "win": "meta",
19
+ "windows": "meta",
20
+ "cmd": "meta",
21
+ "command": "meta",
22
+ "comma": ",",
23
+ "period": ".",
24
+ "quote": "\"",
25
+ "singlequote": "'",
26
+ "colon": ":",
27
+ "semicolon": ";",
28
+ "plus": "+",
29
+ "minus": "-",
30
+ "tilde": "~",
31
+ "equal": "=",
32
+ "slash": "/"
33
+ };
34
+ const controlKeys = [
35
+ "ctrlKey",
36
+ "altKey",
37
+ "shiftKey",
38
+ "metaKey"
39
+ ];
40
+ function registerHotkey(target, hotkey, handler, eventName = "keydown", options) {
41
+ const info = describe(hotkey);
42
+ if (typeof target === "string") {
43
+ target = document.querySelector(target) ?? error(`No element found for selector '${target}'`);
44
+ }
45
+ return listen(target, eventName, function (e) {
46
+ if (!e.target?.closest("[data-hotkey-ignore]")) {
47
+ if (info.code === e.code.toUpperCase()) {
48
+ if (controlKeys.every(n => info[n] === e[n])) {
49
+ handler.call(this, e);
50
+ }
51
+ }
52
+ }
53
+ }, options);
54
+ }
55
+ function describe(hotkey) {
56
+ const keys = hotkey.replace(/\s+/g, "").toLowerCase().split("+");
57
+ const info = keys.reduce((data, k) => {
58
+ k = aliases[k] ?? k;
59
+ switch (k) {
60
+ case "ctrl":
61
+ case "alt":
62
+ case "shift":
63
+ case "meta":
64
+ data[`${k}Key`] = true;
65
+ break;
66
+ default:
67
+ k.length || invalidKey(hotkey);
68
+ k = k.toUpperCase();
69
+ data.code = k.length === 1 && k >= 'A' && k <= 'Z' ? `KEY${k}` : k;
70
+ break;
71
+ }
72
+ return data;
73
+ }, {
74
+ code: "",
75
+ ctrlKey: false,
76
+ altKey: false,
77
+ shiftKey: false,
78
+ metaKey: false
79
+ });
80
+ info.code || invalidKey(hotkey);
81
+ return info;
82
+ }
83
+ function listen(target, type, callback, options) {
84
+ target.addEventListener(type, callback, options);
85
+ return () => target.removeEventListener(type, callback, options);
86
+ }
87
+ function invalidKey(hotkey) {
88
+ error(`Invalid hotkey: '${hotkey}'`);
89
+ }
90
+ function error(message) {
91
+ throw new Error(message);
92
+ }
93
+
94
+ const has_modifier = (modifiers, modifier) => modifiers.includes(modifier);
95
+
96
+ const single = (...fns) => (...args) => {
97
+ for (const fn of fns) {
98
+ fn && fn(...args);
99
+ }
100
+ };
101
+
102
+ const option_keys = ["capture", "passive", "once", "prevent", "stop", "window", "document"];
103
+
104
+ function plugin({ directive }) {
105
+ directive("hotkey", (el, { expression, value, modifiers }, { evaluateLater, cleanup }) => {
106
+ const listener = e => evaluate(() => { }, { scope: { $event: e }, params: [e] });
107
+
108
+ const evaluate = expression
109
+ ? evaluateLater(expression)
110
+ : () => {};
111
+
112
+ const target =
113
+ has_modifier(modifiers, "window")
114
+ ? window
115
+ : has_modifier(modifiers, "document")
116
+ ? document
117
+ : el;
118
+
119
+ const disposes = modifiers
120
+ .filter(m => !option_keys.includes(m))
121
+ .flatMap(s => s.split(","))
122
+ .map(hotkey => registerHotkey(
123
+ target,
124
+ hotkey,
125
+ e => {
126
+ has_modifier(modifiers, "prevent") && e.preventDefault();
127
+ has_modifier(modifiers, "stop") && e.stopPropogation();
128
+
129
+ e.hotkey = hotkey;
130
+ listener(e);
131
+ },
132
+ value || "keydown",
133
+ {
134
+ capture: has_modifier(modifiers, "capture"),
135
+ passive: has_modifier(modifiers, "passive"),
136
+ once: has_modifier(modifiers, "once")
137
+ }));
138
+
139
+ cleanup(single(...disposes));
140
+ });
141
+ }
142
+
143
+ document.addEventListener("alpine:init", () => { Alpine.plugin(plugin); });
144
+
145
+ })();
@@ -0,0 +1 @@
1
+ !function(){"use strict";const e={esc:"escape",ins:"insert",del:"delete",up:"arrowup",down:"arrowdown",right:"arrowright",left:"arrowleft",pgup:"pageup",pgdn:"pagedown",break:"pause",scroll:"scrolllock",scrlk:"scrolllock",prtscr:"printscreen",win:"meta",windows:"meta",cmd:"meta",command:"meta",comma:",",period:".",quote:'"',singlequote:"'",colon:":",semicolon:";",plus:"+",minus:"-",tilde:"~",equal:"=",slash:"/"},t=["ctrlKey","altKey","shiftKey","metaKey"];function o(e){n(`Invalid hotkey: '${e}'`)}function n(e){throw new Error(e)}const r=(e,t)=>e.includes(t),c=["capture","passive","once","prevent","stop","window","document"];function s({directive:s}){s("hotkey",((s,{expression:a,value:i,modifiers:l},{evaluateLater:p,cleanup:u})=>{const d=a?p(a):()=>{},m=r(l,"window")?window:r(l,"document")?document:s;u(((...e)=>(...t)=>{for(const o of e)o&&o(...t)})(...l.filter((e=>!c.includes(e))).flatMap((e=>e.split(","))).map((c=>function(r,c,s,a="keydown",i){const l=function(t){const n=t.replace(/\s+/g,"").toLowerCase().split("+").reduce(((n,r)=>{switch(r=e[r]??r){case"ctrl":case"alt":case"shift":case"meta":n[`${r}Key`]=!0;break;default:r.length||o(t),r=r.toUpperCase(),n.code=1!==r.length||"A">r||r>"Z"?r:`KEY${r}`}return n}),{code:"",ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1});return n.code||o(t),n}(c);return"string"==typeof r&&(r=document.querySelector(r)??n(`No element found for selector '${r}'`)),function(e,t,o,n){return e.addEventListener(t,o,n),()=>e.removeEventListener(t,o,n)}(r,a,(function(e){e.target?.closest("[data-hotkey-ignore]")||l.code===e.code.toUpperCase()&&t.every((t=>l[t]===e[t]))&&s.call(this,e)}),i)}(m,c,(e=>{r(l,"prevent")&&e.preventDefault(),r(l,"stop")&&e.stopPropogation(),e.hotkey=c,(e=>{d((()=>{}),{scope:{$event:e},params:[e]})})(e)}),i||"keydown",{capture:r(l,"capture"),passive:r(l,"passive"),once:r(l,"once")})))))}))}document.addEventListener("alpine:init",(()=>{Alpine.plugin(s)}))}();
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "@ramstack/alpinegear-hotkey",
3
+ "version": "1.0.0-preview.1",
4
+ "description": "@ramstack/alpinegear-hotkey provides 'x-hotkey' Alpine.js directive, allowing easily handle keyboard shortcuts.",
5
+ "author": "Rameel Burhan",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/rameel/ramstack.alpinegear.js.git",
10
+ "directory": "src/plugins/hotkey"
11
+ },
12
+ "keywords": [
13
+ "alpine.js",
14
+ "alpinejs"
15
+ ],
16
+ "main": "alpinegear-hotkey.js",
17
+ "module": "alpinegear-hotkey.esm.js"
18
+ }