@cxl/keyboard 0.1.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 CHANGED
@@ -2,16 +2,15 @@
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/%40cxl%2Fkeyboard.svg)](https://badge.fury.io/js/%40cxl%2Fkeyboard)
4
4
 
5
- Keyboard Handling Library
5
+ Lightweight module for handling keyboard input on HTML elements with customizable layouts and configurable key sequence timing. Provides utilities to parse, normalize, and translate key events into standardized string representations, with support for modifier keys and platform-specific conventions.
6
6
 
7
7
  ## Project Details
8
8
 
9
- - Branch Version: [0.1.0](https://npmjs.com/package/@cxl/keyboard/v/0.1.0)
10
- - License: UNLICENSED
11
- - Documentation: [Link](https://cxlio.github.io/cxl/keyboard)
12
- - Report Issues: [Github](https://github.com/cxlio/cxl/issues)
9
+ - Branch Version: [1.1.0](https://npmjs.com/package/@cxl/keyboard/v/1.1.0)
10
+ - License: GPL-3.0
11
+ - Documentation: [Link](https://cxlio.github.io/docs/@cxl/keyboard)
12
+ - Report Issues: [Github](https://github.com/cxlio/open/issues)
13
13
 
14
14
  ## Installation
15
15
 
16
16
  npm install @cxl/keyboard
17
-
@@ -0,0 +1 @@
1
+ var L=typeof window<"u"?window.navigator:{language:"en-US",platform:"nodejs"},A=/Mac|iPod|iPhone|iPad/,C=/(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g,D={"?":"/",">":".","<":",",'"':"'",":":";","{":"[","}":"]","|":"\\","~":"`","+":"=",_:"-","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0"},M={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc",Space:"space",Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Quote:"'",Backslash:"\\",Apostrophe:"'",Semicolon:";",Comma:",",Period:".",Slash:"/"},d={shiftMap:D,translate({code:e,key:o}){let r=M[e];return r||(e.startsWith("Key")?e.slice(3).toLowerCase():e.startsWith("Digit")?e.slice(5):o.toLowerCase())}},q={"en-US":d};function k(e,{translate:o,altName:r,modName:i}){let n=e.key;if(!n||n==="Shift"||n==="Alt"||n==="Meta"||n==="Control"||n==="Dead"&&!e.altKey)return"";let s=o(e),t;return e.ctrlKey&&(t="ctrl"),e.altKey&&(t=t?t+"+"+r:r),e.shiftKey&&(t=t?t+"+shift":"shift"),e.metaKey&&(t=t?t+"+"+i:i),t?t+"+"+s:s}function P({element:e,onKey:o,delay:r,layout:i,capture:n}){let s=r===void 0?250:r,t=[],a=0,f=!1;i??=h();let S=m(i);function p(c){if(f||c.isComposing||c.keyCode===229||c.getModifierState("AltGraph"))return;let l=k(c,S),u=Date.now();if(!l)return;u-a<s?t.push(l):t=[l];let y=t.slice(0);do{if(o(y.join(" "),t)!==!1){c.stopPropagation(),c.preventDefault(),u=0;break}y.shift()}while(y.length);a=u}function K(){f=!0,t=[],a=0}function w(){f=!1}return e.addEventListener("compositionstart",K,{capture:n}),e.addEventListener("compositionend",w,{capture:n}),e.addEventListener("keydown",p,{capture:n}),()=>{e.removeEventListener("compositionstart",K,{capture:n}),e.removeEventListener("compositionend",w,{capture:n}),e.removeEventListener("keydown",p,{capture:n})}}function h(){return q[L.language]??d}function g(){return{ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:"",code:""}}function E(e,{modKey:o,shiftMap:r}){let i=[],n,s=g();for(;n=C.exec(e.toLowerCase());){let t=n[1]??"";if(t==="shift")s.shiftKey=!0;else if(t==="ctrl"||t==="control")s.ctrlKey=!0;else if(t==="alt"||t==="option")s.altKey=!0;else if(t==="meta"||t==="cmd"||t==="command")s.metaKey=!0;else if(t==="mod")s[o]=!0;else{let a=r[t];a?(s.key=a,s.shiftKey=!0):s.key=t}n[2]!=="+"&&(i.push(s),s=g())}return i}function m(e){let o=A.test(L.platform);return{...d,modKey:o?"metaKey":"ctrlKey",altName:o?"option":"alt",modName:o?"cmd":"meta",...e}}function x(e,o=h()){return E(e,m(o))}function b(e,o=h()){let r=m(o);return E(e,r).map(n=>k(n,r)).join(" ")}export{q as KeyboardLayoutData,d as enUsKeyboardLayout,P as handleKeyboard,b as normalize,x as parseKey};
package/index.d.ts CHANGED
@@ -1,16 +1,16 @@
1
- /// <amd-module name="@cxl/keyboard" />
2
- interface Key {
1
+ interface __dts_0_Key {
3
2
  ctrlKey: boolean;
4
3
  altKey: boolean;
5
4
  shiftKey: boolean;
6
5
  metaKey: boolean;
7
6
  key: string;
7
+ code: string;
8
8
  }
9
9
  /**
10
10
  * The `KeyboardOptions` interface defines the configuration needed to handle keyboard interactions with
11
11
  * a specific HTML element.
12
12
  */
13
- export interface KeyboardOptions {
13
+ interface KeyboardOptions {
14
14
  /**
15
15
  * Specifies the HTML element on which keyboard events are captured.
16
16
  * This element will receive focus and listen for key events.
@@ -38,12 +38,41 @@ export interface KeyboardOptions {
38
38
  */
39
39
  capture?: boolean;
40
40
  }
41
- export interface KeyboardLayout {
42
- shiftedKeys: string[];
43
- shiftMap: Record<string, string>;
44
- modKey: 'metaKey' | 'ctrlKey';
41
+ /**
42
+ * The `KeyboardLayout` interface describes how a keyboard layout should be structured internally.
43
+ */
44
+ interface KeyboardLayout {
45
+ /**
46
+ * A mapping of shifted keys to their non-shifted counterparts, used to accurately
47
+ * interpret which character a shifted key press represents.
48
+ */
49
+ shiftMap?: Record<string, string | undefined>;
50
+ /**
51
+ * Indicates whether the 'meta' or 'ctrl' key is the primary modifier used for commands,
52
+ * differing based on the operating system (e.g., 'metaKey' for macOS).
53
+ */
54
+ modKey?: 'metaKey' | 'ctrlKey';
55
+ altName?: 'option' | 'alt';
56
+ modName?: 'meta' | 'cmd';
57
+ /**
58
+ * Describes a function that translates a `Key` object (representing a keyboard event) to a character string.
59
+ */
60
+ translate?(ev: __dts_0_Key): string;
45
61
  }
46
- export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
62
+ declare const enUsKeyboardLayout: {
63
+ shiftMap: Record<string, string | undefined>;
64
+ /**
65
+ * The `translate` method converts a `Key` event into a string representation.
66
+ * Firstly, it checks the `TranslateKey` map for special keys (like arrows or space),
67
+ * which have predefined string values. For keys corresponding to
68
+ * alphabet letters and numbers, the method derives the letter from
69
+ * the key `code`, ensuring it's lowercase for uniformity.
70
+ * If none of these match, it defaults to using the `key` property,
71
+ * which allows handling other miscellaneous keys gracefully.
72
+ */
73
+ translate({ code, key }: __dts_0_Key): string;
74
+ };
75
+ declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
47
76
  /**
48
77
  * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
49
78
  * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
@@ -62,25 +91,16 @@ export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
62
91
  * browser actions.
63
92
  * @return A cleanup function that removes the event listener.
64
93
  */
65
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
66
- /**
67
- * This function, `parseKey`, takes a key combination string and splits it into a sequence of `Key` objects.
68
- * It uses regular expressions to identify each part of the key combination, accounting for modifier keys
69
- * like 'shift', 'ctrl', 'alt', 'meta', and 'mod', the latter being dependent on the `modKey` from the
70
- * `KeyboardLayout` (either 'ctrlKey' or 'metaKey' depending on the platform). For non-modifier keys, it
71
- * checks if the `shiftKey` is active and if the key should be shifted using the `shiftMap`. This logic
72
- * ensures the function captures accurate key state details in preparation for further handling like matching
73
- * key sequences in the `handleKeyboard` function.
74
- */
75
- export declare function parseKey(key: string, { modKey, shiftedKeys, shiftMap }?: KeyboardLayout): Key[];
94
+ declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
95
+ declare function parseKey(key: string, layout?: KeyboardLayout): __dts_0_Key[];
76
96
  /**
77
97
  * Converts a string representing a key combination into a normalized string format.
78
98
  * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
99
+ *
79
100
  * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
80
101
  * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
81
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
82
- * strings are concatenated with spaces and returned as the normalized form. This is useful
102
+ * considering the layout's details. This is useful
83
103
  * for ensuring consistent representation of key sequences across different keyboard layouts.
84
104
  */
85
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
86
- export {};
105
+ declare function normalize(key: string, layout?: KeyboardLayout): string;
106
+ export { handleKeyboard, parseKey, normalize, KeyboardOptions, KeyboardLayout, enUsKeyboardLayout, KeyboardLayoutData };
package/package.json CHANGED
@@ -1,26 +1,23 @@
1
1
  {
2
2
  "name": "@cxl/keyboard",
3
- "version": "0.1.0",
4
- "description": "Keyboard Handling Library",
5
- "license": "UNLICENSED",
3
+ "version": "1.1.0",
4
+ "description": "Lightweight module for handling keyboard input on HTML elements with customizable layouts and configurable key sequence timing. Provides utilities to parse, normalize, and translate key events into standardized string representations, with support for modifier keys and platform-specific conventions.",
5
+ "license": "GPL-3.0",
6
6
  "files": [
7
7
  "*.js",
8
8
  "*.d.ts",
9
9
  "*.css",
10
- "amd/*.js",
11
- "amd/*.d.ts",
12
- "mjs/*.js",
13
- "mjs/*.d.ts",
14
- "LICENSE",
10
+ "LICENSE.md",
15
11
  "*.md"
16
12
  ],
17
- "main": "index.js",
18
- "browser": "amd/index.js",
19
- "homepage": "https://cxlio.github.io/cxl/keyboard",
20
- "bugs": "https://github.com/cxlio/cxl/issues",
13
+ "main": "./index.bundle.js",
14
+ "browser": "./index.bundle.js",
15
+ "homepage": "https://cxlio.github.io/docs/@cxl/keyboard",
16
+ "bugs": "https://github.com/cxlio/open/issues",
21
17
  "repository": {
22
18
  "type": "git",
23
- "url": "https://github.com/cxlio/cxl.git",
19
+ "url": "https://github.com/cxlio/open.git",
24
20
  "directory": "keyboard"
25
- }
21
+ },
22
+ "type": "module"
26
23
  }
package/amd/index.d.ts DELETED
@@ -1,86 +0,0 @@
1
- /// <amd-module name="@cxl/keyboard" />
2
- interface Key {
3
- ctrlKey: boolean;
4
- altKey: boolean;
5
- shiftKey: boolean;
6
- metaKey: boolean;
7
- key: string;
8
- }
9
- /**
10
- * The `KeyboardOptions` interface defines the configuration needed to handle keyboard interactions with
11
- * a specific HTML element.
12
- */
13
- export interface KeyboardOptions {
14
- /**
15
- * Specifies the HTML element on which keyboard events are captured.
16
- * This element will receive focus and listen for key events.
17
- */
18
- element: HTMLElement;
19
- /**
20
- * A callback function that processes key events. It receives the current key being pressed
21
- * and the sequence of keys accumulated so far. It returns `true` or `false` to indicate whether
22
- * the sequence was consumed.
23
- */
24
- onKey: (key: string, sequence: string[]) => boolean;
25
- /**
26
- * The time in milliseconds to wait between key presses before resetting the sequence.
27
- * Defaults to 250ms if not provided, ensuring thoughtful key sequences rather than accidental key presses.
28
- */
29
- delay?: number;
30
- /**
31
- * Optional parameter to specify a custom `KeyboardLayout`.
32
- * Defaults to 'en-US' if not provided. This affects how key combinations and modifier keys are interpreted.
33
- */
34
- layout?: KeyboardLayout;
35
- /**
36
- * Boolean indicating whether to capture key events in the capture phase.
37
- * This determines when the event listener reacts in the event propagation flow.
38
- */
39
- capture?: boolean;
40
- }
41
- export interface KeyboardLayout {
42
- shiftedKeys: string[];
43
- shiftMap: Record<string, string>;
44
- modKey: 'metaKey' | 'ctrlKey';
45
- }
46
- export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
47
- /**
48
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
49
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
50
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
51
- * layout, and an optional capture mode for events.
52
- *
53
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
54
- * key presses as part of the same sequence or a new one.
55
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
56
- * (especially with modifiers) are interpreted.
57
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
58
- * as propagation and default handling based on the `onKey` callback result.
59
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
60
- * stopping event propagation based on handler response.
61
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
62
- * browser actions.
63
- * @return A cleanup function that removes the event listener.
64
- */
65
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
66
- /**
67
- * This function, `parseKey`, takes a key combination string and splits it into a sequence of `Key` objects.
68
- * It uses regular expressions to identify each part of the key combination, accounting for modifier keys
69
- * like 'shift', 'ctrl', 'alt', 'meta', and 'mod', the latter being dependent on the `modKey` from the
70
- * `KeyboardLayout` (either 'ctrlKey' or 'metaKey' depending on the platform). For non-modifier keys, it
71
- * checks if the `shiftKey` is active and if the key should be shifted using the `shiftMap`. This logic
72
- * ensures the function captures accurate key state details in preparation for further handling like matching
73
- * key sequences in the `handleKeyboard` function.
74
- */
75
- export declare function parseKey(key: string, { modKey, shiftedKeys, shiftMap }?: KeyboardLayout): Key[];
76
- /**
77
- * Converts a string representing a key combination into a normalized string format.
78
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
79
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
80
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
81
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
82
- * strings are concatenated with spaces and returned as the normalized form. This is useful
83
- * for ensuring consistent representation of key sequences across different keyboard layouts.
84
- */
85
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
86
- export {};
package/amd/index.js DELETED
@@ -1 +0,0 @@
1
- define("@cxl/keyboard",["require","exports"],(function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeyboardLayoutData=void 0,t.handleKeyboard=function({element:e,onKey:a,delay:n,layout:r,capture:s}){const y=void 0===n?250:n,l=o.language;let c=[],f=0;const d=r||t.KeyboardLayoutData[l]||t.KeyboardLayoutData["en-US"];function u(e){const t=i(e,d);let o=Date.now();if(!t)return;o-f<y?c.push(t):c=[t];const n=c.slice(0);do{if(!1!==a(n.join(" "),c)){e.stopPropagation(),e.preventDefault(),o=0;break}n.shift()}while(n.length);f=o}return e.addEventListener("keydown",u,{capture:s}),()=>e.removeEventListener("keydown",u,{capture:s})},t.parseKey=y,t.normalize=function(e,t=s()){return y(e,t).map((e=>i(e,t))).join(" ")};const o="undefined"!=typeof window?window.navigator:{language:"en-US",platform:"nodejs"},a=/(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g,n={"/":"?",".":">",",":"<","'":'"',";":":","[":"{","]":"}","\\":"|","`":"~","=":"+","-":"_",1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")"};t.KeyboardLayoutData={"en-US":{shiftedKeys:Object.values(n),shiftMap:n,modKey:/Mac|iPod|iPhone|iPad/.test(o.platform)?"metaKey":"ctrlKey"}};const r={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc"," ":"space"};function i(e,{shiftedKeys:t}){const o=e.key;if(!o||"Shift"===o||"Alt"===o||"Meta"===o||"Control"===o)return"";const a=r[o]||o.toLowerCase();let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&!t.includes(a)&&(n=n?n+"+shift":"shift"),e.metaKey&&(n=n?n+"+meta":"meta"),n?n+"+"+a:a}function s(){return t.KeyboardLayoutData[o?.language]||t.KeyboardLayoutData["en-US"]}function y(e,{modKey:t,shiftedKeys:o,shiftMap:n}=s()){const r=[];let i,y={ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:""};for(;i=a.exec(e.toLowerCase());){const e=i[1];if("shift"===e)y.shiftKey=!0;else if("ctrl"===e||"control"===e)y.ctrlKey=!0;else if("alt"===e||"option"===e)y.altKey=!0;else if("meta"===e||"cmd"===e||"command"===e)y.metaKey=!0;else if("mod"===e)y[t]=!0;else if(y.key=e,y.shiftKey)if(o.includes(e))y.shiftKey=!1;else{const t=n[e];t&&(y.key=t,y.shiftKey=!1)}"+"!==i[2]&&(r.push(y),y={ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:""})}return r}}));
package/index.js DELETED
@@ -1,198 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeyboardLayoutData = void 0;
4
- exports.handleKeyboard = handleKeyboard;
5
- exports.parseKey = parseKey;
6
- exports.normalize = normalize;
7
- ///<amd-module name="@cxl/keyboard"/>
8
- const navigator = typeof window !== 'undefined'
9
- ? window.navigator
10
- : { language: 'en-US', platform: 'nodejs' };
11
- const IS_MAC = /Mac|iPod|iPhone|iPad/;
12
- const PARSE_KEY = /(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g;
13
- const SHIFT_MAP = {
14
- '/': '?',
15
- '.': '>',
16
- ',': '<',
17
- "'": '"',
18
- ';': ':',
19
- '[': '{',
20
- ']': '}',
21
- '\\': '|',
22
- '`': '~',
23
- '=': '+',
24
- '-': '_',
25
- '1': '!',
26
- '2': '@',
27
- '3': '#',
28
- '4': '$',
29
- '5': '%',
30
- '6': '^',
31
- '7': '&',
32
- '8': '*',
33
- '9': '(',
34
- '0': ')',
35
- };
36
- exports.KeyboardLayoutData = {
37
- 'en-US': {
38
- shiftedKeys: Object.values(SHIFT_MAP),
39
- shiftMap: SHIFT_MAP,
40
- modKey: IS_MAC.test(navigator.platform) ? 'metaKey' : 'ctrlKey',
41
- },
42
- };
43
- const TranslateKey = {
44
- ArrowUp: 'up',
45
- ArrowDown: 'down',
46
- ArrowLeft: 'left',
47
- ArrowRight: 'right',
48
- Escape: 'esc',
49
- ' ': 'space',
50
- };
51
- /**
52
- * This function converts a `Key` event into a string representation, encoding modifier keys
53
- * (ctrl, alt, shift, meta) and the key itself. It checks each modifier key flag in the `Key`
54
- * object, constructing a result string with '+' separators. Non-modifier keys are lowercased
55
- * and looked up in `TranslateKey` for a more readable name. If the key itself is a shifted
56
- * character (not included in `shiftedKeys`), 'shift' is added to the modifiers. This string
57
- * format is useful for handling complex keyboard shortcuts consistently across different layouts.
58
- */
59
- function keyboardEventToString(ev, { shiftedKeys }) {
60
- const key = ev.key;
61
- if (!key ||
62
- key === 'Shift' ||
63
- key === 'Alt' ||
64
- key === 'Meta' ||
65
- key === 'Control')
66
- return '';
67
- const ch = TranslateKey[key] || key.toLowerCase();
68
- let result;
69
- if (ev.ctrlKey)
70
- result = 'ctrl';
71
- if (ev.altKey)
72
- result = result ? result + '+alt' : 'alt';
73
- if (ev.shiftKey && !shiftedKeys.includes(ch))
74
- result = result ? result + '+shift' : 'shift';
75
- if (ev.metaKey)
76
- result = result ? result + '+meta' : 'meta';
77
- return result ? result + '+' + ch : ch;
78
- }
79
- /**
80
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
81
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
82
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
83
- * layout, and an optional capture mode for events.
84
- *
85
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
86
- * key presses as part of the same sequence or a new one.
87
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
88
- * (especially with modifiers) are interpreted.
89
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
90
- * as propagation and default handling based on the `onKey` callback result.
91
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
92
- * stopping event propagation based on handler response.
93
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
94
- * browser actions.
95
- * @return A cleanup function that removes the event listener.
96
- */
97
- function handleKeyboard({ element, onKey, delay, layout, capture, }) {
98
- const D = delay === undefined ? 250 : delay;
99
- const locale = navigator.language;
100
- let sequence = [];
101
- let lastT = 0;
102
- const newLayout = layout || exports.KeyboardLayoutData[locale] || exports.KeyboardLayoutData['en-US'];
103
- function handler(ev) {
104
- const k = keyboardEventToString(ev, newLayout);
105
- let t = Date.now();
106
- if (!k)
107
- return;
108
- if (t - lastT < D)
109
- sequence.push(k);
110
- else
111
- sequence = [k];
112
- const seq = sequence.slice(0);
113
- do {
114
- if (onKey(seq.join(' '), sequence) !== false) {
115
- ev.stopPropagation();
116
- ev.preventDefault();
117
- t = 0;
118
- break;
119
- }
120
- seq.shift();
121
- } while (seq.length);
122
- lastT = t;
123
- }
124
- element.addEventListener('keydown', handler, { capture });
125
- return () => element.removeEventListener('keydown', handler, { capture });
126
- }
127
- function getDefaultLayout() {
128
- return (exports.KeyboardLayoutData[navigator?.language] || exports.KeyboardLayoutData['en-US']);
129
- }
130
- function newKey() {
131
- return {
132
- ctrlKey: false,
133
- shiftKey: false,
134
- metaKey: false,
135
- altKey: false,
136
- key: '',
137
- };
138
- }
139
- /**
140
- * This function, `parseKey`, takes a key combination string and splits it into a sequence of `Key` objects.
141
- * It uses regular expressions to identify each part of the key combination, accounting for modifier keys
142
- * like 'shift', 'ctrl', 'alt', 'meta', and 'mod', the latter being dependent on the `modKey` from the
143
- * `KeyboardLayout` (either 'ctrlKey' or 'metaKey' depending on the platform). For non-modifier keys, it
144
- * checks if the `shiftKey` is active and if the key should be shifted using the `shiftMap`. This logic
145
- * ensures the function captures accurate key state details in preparation for further handling like matching
146
- * key sequences in the `handleKeyboard` function.
147
- */
148
- function parseKey(key, { modKey, shiftedKeys, shiftMap } = getDefaultLayout()) {
149
- const sequence = [];
150
- let match;
151
- let event = newKey();
152
- while ((match = PARSE_KEY.exec(key.toLowerCase()))) {
153
- const ch = match[1];
154
- if (ch === 'shift')
155
- event.shiftKey = true;
156
- else if (ch === 'ctrl' || ch === 'control')
157
- event.ctrlKey = true;
158
- else if (ch === 'alt' || ch === 'option')
159
- event.altKey = true;
160
- else if (ch === 'meta' || ch === 'cmd' || ch === 'command')
161
- event.metaKey = true;
162
- else if (ch === 'mod')
163
- event[modKey] = true;
164
- else {
165
- event.key = ch;
166
- if (event.shiftKey) {
167
- if (shiftedKeys.includes(ch)) {
168
- event.shiftKey = false;
169
- }
170
- else {
171
- const shifted = shiftMap[ch];
172
- if (shifted) {
173
- event.key = shifted;
174
- event.shiftKey = false;
175
- }
176
- }
177
- }
178
- }
179
- if (match[2] !== '+') {
180
- sequence.push(event);
181
- event = newKey();
182
- }
183
- }
184
- return sequence;
185
- }
186
- /**
187
- * Converts a string representing a key combination into a normalized string format.
188
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
189
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
190
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
191
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
192
- * strings are concatenated with spaces and returned as the normalized form. This is useful
193
- * for ensuring consistent representation of key sequences across different keyboard layouts.
194
- */
195
- function normalize(key, layout = getDefaultLayout()) {
196
- const sequence = parseKey(key, layout);
197
- return sequence.map(key => keyboardEventToString(key, layout)).join(' ');
198
- }
package/index.min.js DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeyboardLayoutData=void 0,exports.handleKeyboard=handleKeyboard,exports.parseKey=parseKey,exports.normalize=normalize;const navigator="undefined"!=typeof window?window.navigator:{language:"en-US",platform:"nodejs"},IS_MAC=/Mac|iPod|iPhone|iPad/,PARSE_KEY=/(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g,SHIFT_MAP={"/":"?",".":">",",":"<","'":'"',";":":","[":"{","]":"}","\\":"|","`":"~","=":"+","-":"_",1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")"};exports.KeyboardLayoutData={"en-US":{shiftedKeys:Object.values(SHIFT_MAP),shiftMap:SHIFT_MAP,modKey:IS_MAC.test(navigator.platform)?"metaKey":"ctrlKey"}};const TranslateKey={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc"," ":"space"};function keyboardEventToString(e,{shiftedKeys:t}){const o=e.key;if(!o||"Shift"===o||"Alt"===o||"Meta"===o||"Control"===o)return"";const a=TranslateKey[o]||o.toLowerCase();let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&!t.includes(a)&&(n=n?n+"+shift":"shift"),e.metaKey&&(n=n?n+"+meta":"meta"),n?n+"+"+a:a}function handleKeyboard({element:e,onKey:t,delay:o,layout:a,capture:n}){const r=void 0===o?250:o,s=navigator.language;let i=[],y=0;const l=a||exports.KeyboardLayoutData[s]||exports.KeyboardLayoutData["en-US"];function d(e){const o=keyboardEventToString(e,l);let a=Date.now();if(!o)return;a-y<r?i.push(o):i=[o];const n=i.slice(0);do{if(!1!==t(n.join(" "),i)){e.stopPropagation(),e.preventDefault(),a=0;break}n.shift()}while(n.length);y=a}return e.addEventListener("keydown",d,{capture:n}),()=>e.removeEventListener("keydown",d,{capture:n})}function getDefaultLayout(){return exports.KeyboardLayoutData[navigator?.language]||exports.KeyboardLayoutData["en-US"]}function newKey(){return{ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:""}}function parseKey(e,{modKey:t,shiftedKeys:o,shiftMap:a}=getDefaultLayout()){const n=[];let r,s=newKey();for(;r=PARSE_KEY.exec(e.toLowerCase());){const e=r[1];if("shift"===e)s.shiftKey=!0;else if("ctrl"===e||"control"===e)s.ctrlKey=!0;else if("alt"===e||"option"===e)s.altKey=!0;else if("meta"===e||"cmd"===e||"command"===e)s.metaKey=!0;else if("mod"===e)s[t]=!0;else if(s.key=e,s.shiftKey)if(o.includes(e))s.shiftKey=!1;else{const t=a[e];t&&(s.key=t,s.shiftKey=!1)}"+"!==r[2]&&(n.push(s),s=newKey())}return n}function normalize(e,t=getDefaultLayout()){return parseKey(e,t).map((e=>keyboardEventToString(e,t))).join(" ")}
package/mjs/index.d.ts DELETED
@@ -1,85 +0,0 @@
1
- interface Key {
2
- ctrlKey: boolean;
3
- altKey: boolean;
4
- shiftKey: boolean;
5
- metaKey: boolean;
6
- key: string;
7
- }
8
- /**
9
- * The `KeyboardOptions` interface defines the configuration needed to handle keyboard interactions with
10
- * a specific HTML element.
11
- */
12
- export interface KeyboardOptions {
13
- /**
14
- * Specifies the HTML element on which keyboard events are captured.
15
- * This element will receive focus and listen for key events.
16
- */
17
- element: HTMLElement;
18
- /**
19
- * A callback function that processes key events. It receives the current key being pressed
20
- * and the sequence of keys accumulated so far. It returns `true` or `false` to indicate whether
21
- * the sequence was consumed.
22
- */
23
- onKey: (key: string, sequence: string[]) => boolean;
24
- /**
25
- * The time in milliseconds to wait between key presses before resetting the sequence.
26
- * Defaults to 250ms if not provided, ensuring thoughtful key sequences rather than accidental key presses.
27
- */
28
- delay?: number;
29
- /**
30
- * Optional parameter to specify a custom `KeyboardLayout`.
31
- * Defaults to 'en-US' if not provided. This affects how key combinations and modifier keys are interpreted.
32
- */
33
- layout?: KeyboardLayout;
34
- /**
35
- * Boolean indicating whether to capture key events in the capture phase.
36
- * This determines when the event listener reacts in the event propagation flow.
37
- */
38
- capture?: boolean;
39
- }
40
- export interface KeyboardLayout {
41
- shiftedKeys: string[];
42
- shiftMap: Record<string, string>;
43
- modKey: 'metaKey' | 'ctrlKey';
44
- }
45
- export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
46
- /**
47
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
48
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
49
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
50
- * layout, and an optional capture mode for events.
51
- *
52
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
53
- * key presses as part of the same sequence or a new one.
54
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
55
- * (especially with modifiers) are interpreted.
56
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
57
- * as propagation and default handling based on the `onKey` callback result.
58
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
59
- * stopping event propagation based on handler response.
60
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
61
- * browser actions.
62
- * @return A cleanup function that removes the event listener.
63
- */
64
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
65
- /**
66
- * This function, `parseKey`, takes a key combination string and splits it into a sequence of `Key` objects.
67
- * It uses regular expressions to identify each part of the key combination, accounting for modifier keys
68
- * like 'shift', 'ctrl', 'alt', 'meta', and 'mod', the latter being dependent on the `modKey` from the
69
- * `KeyboardLayout` (either 'ctrlKey' or 'metaKey' depending on the platform). For non-modifier keys, it
70
- * checks if the `shiftKey` is active and if the key should be shifted using the `shiftMap`. This logic
71
- * ensures the function captures accurate key state details in preparation for further handling like matching
72
- * key sequences in the `handleKeyboard` function.
73
- */
74
- export declare function parseKey(key: string, { modKey, shiftedKeys, shiftMap }?: KeyboardLayout): Key[];
75
- /**
76
- * Converts a string representing a key combination into a normalized string format.
77
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
78
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
79
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
80
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
81
- * strings are concatenated with spaces and returned as the normalized form. This is useful
82
- * for ensuring consistent representation of key sequences across different keyboard layouts.
83
- */
84
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
85
- export {};
package/mjs/index.js DELETED
@@ -1 +0,0 @@
1
- const navigator="undefined"!=typeof window?window.navigator:{language:"en-US",platform:"nodejs"},IS_MAC=/Mac|iPod|iPhone|iPad/,PARSE_KEY=/(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g,SHIFT_MAP={"/":"?",".":">",",":"<","'":'"',";":":","[":"{","]":"}","\\":"|","`":"~","=":"+","-":"_",1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")"};export const KeyboardLayoutData={"en-US":{shiftedKeys:Object.values(SHIFT_MAP),shiftMap:SHIFT_MAP,modKey:IS_MAC.test(navigator.platform)?"metaKey":"ctrlKey"}};const TranslateKey={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc"," ":"space"};function keyboardEventToString(e,{shiftedKeys:t}){const o=e.key;if(!o||"Shift"===o||"Alt"===o||"Meta"===o||"Control"===o)return"";const a=TranslateKey[o]||o.toLowerCase();let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&!t.includes(a)&&(n=n?n+"+shift":"shift"),e.metaKey&&(n=n?n+"+meta":"meta"),n?n+"+"+a:a}export function handleKeyboard({element:e,onKey:t,delay:o,layout:a,capture:n}){const r=void 0===o?250:o,i=navigator.language;let s=[],y=0;const l=a||KeyboardLayoutData[i]||KeyboardLayoutData["en-US"];function f(e){const o=keyboardEventToString(e,l);let a=Date.now();if(!o)return;a-y<r?s.push(o):s=[o];const n=s.slice(0);do{if(!1!==t(n.join(" "),s)){e.stopPropagation(),e.preventDefault(),a=0;break}n.shift()}while(n.length);y=a}return e.addEventListener("keydown",f,{capture:n}),()=>e.removeEventListener("keydown",f,{capture:n})}function getDefaultLayout(){return KeyboardLayoutData[navigator?.language]||KeyboardLayoutData["en-US"]}function newKey(){return{ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:""}}export function parseKey(e,{modKey:t,shiftedKeys:o,shiftMap:a}=getDefaultLayout()){const n=[];let r,i=newKey();for(;r=PARSE_KEY.exec(e.toLowerCase());){const e=r[1];if("shift"===e)i.shiftKey=!0;else if("ctrl"===e||"control"===e)i.ctrlKey=!0;else if("alt"===e||"option"===e)i.altKey=!0;else if("meta"===e||"cmd"===e||"command"===e)i.metaKey=!0;else if("mod"===e)i[t]=!0;else if(i.key=e,i.shiftKey)if(o.includes(e))i.shiftKey=!1;else{const t=a[e];t&&(i.key=t,i.shiftKey=!1)}"+"!==r[2]&&(n.push(i),i=newKey())}return n}export function normalize(e,t=getDefaultLayout()){return parseKey(e,t).map((e=>keyboardEventToString(e,t))).join(" ")}
package/test.d.ts DELETED
@@ -1,2 +0,0 @@
1
- declare const _default: import("@cxl/spec").Test;
2
- export default _default;