@cxl/keyboard 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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: [1.0.0](https://npmjs.com/package/@cxl/keyboard/v/1.0.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,5 +1,4 @@
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;
@@ -11,7 +10,7 @@ interface Key {
11
10
  * The `KeyboardOptions` interface defines the configuration needed to handle keyboard interactions with
12
11
  * a specific HTML element.
13
12
  */
14
- export interface KeyboardOptions {
13
+ interface KeyboardOptions {
15
14
  /**
16
15
  * Specifies the HTML element on which keyboard events are captured.
17
16
  * This element will receive focus and listen for key events.
@@ -42,23 +41,38 @@ export interface KeyboardOptions {
42
41
  /**
43
42
  * The `KeyboardLayout` interface describes how a keyboard layout should be structured internally.
44
43
  */
45
- export interface KeyboardLayout {
44
+ interface KeyboardLayout {
46
45
  /**
47
46
  * A mapping of shifted keys to their non-shifted counterparts, used to accurately
48
47
  * interpret which character a shifted key press represents.
49
48
  */
50
- shiftMap: Record<string, string | undefined>;
51
- /**
52
- * Maps the representation of keys when combined with the alt key.
53
- */
54
- translate(ev: Key): string;
49
+ shiftMap?: Record<string, string | undefined>;
55
50
  /**
56
51
  * Indicates whether the 'meta' or 'ctrl' key is the primary modifier used for commands,
57
52
  * differing based on the operating system (e.g., 'metaKey' for macOS).
58
53
  */
59
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;
60
61
  }
61
- 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>;
62
76
  /**
63
77
  * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
64
78
  * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
@@ -77,16 +91,16 @@ export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
77
91
  * browser actions.
78
92
  * @return A cleanup function that removes the event listener.
79
93
  */
80
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
81
- export declare function parseKey(key: string, layout?: KeyboardLayout): Key[];
94
+ declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
95
+ declare function parseKey(key: string, layout?: KeyboardLayout): __dts_0_Key[];
82
96
  /**
83
97
  * Converts a string representing a key combination into a normalized string format.
84
98
  * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
99
+ *
85
100
  * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
86
101
  * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
87
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
88
- * strings are concatenated with spaces and returned as the normalized form. This is useful
102
+ * considering the layout's details. This is useful
89
103
  * for ensuring consistent representation of key sequences across different keyboard layouts.
90
104
  */
91
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
92
- 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": "1.0.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,92 +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
- code: string;
9
- }
10
- /**
11
- * The `KeyboardOptions` interface defines the configuration needed to handle keyboard interactions with
12
- * a specific HTML element.
13
- */
14
- export interface KeyboardOptions {
15
- /**
16
- * Specifies the HTML element on which keyboard events are captured.
17
- * This element will receive focus and listen for key events.
18
- */
19
- element: HTMLElement;
20
- /**
21
- * A callback function that processes key events. It receives the current key being pressed
22
- * and the sequence of keys accumulated so far. It returns `true` or `false` to indicate whether
23
- * the sequence was consumed.
24
- */
25
- onKey: (key: string, sequence: string[]) => boolean;
26
- /**
27
- * The time in milliseconds to wait between key presses before resetting the sequence.
28
- * Defaults to 250ms if not provided, ensuring thoughtful key sequences rather than accidental key presses.
29
- */
30
- delay?: number;
31
- /**
32
- * Optional parameter to specify a custom `KeyboardLayout`.
33
- * Defaults to 'en-US' if not provided. This affects how key combinations and modifier keys are interpreted.
34
- */
35
- layout?: KeyboardLayout;
36
- /**
37
- * Boolean indicating whether to capture key events in the capture phase.
38
- * This determines when the event listener reacts in the event propagation flow.
39
- */
40
- capture?: boolean;
41
- }
42
- /**
43
- * The `KeyboardLayout` interface describes how a keyboard layout should be structured internally.
44
- */
45
- export interface KeyboardLayout {
46
- /**
47
- * A mapping of shifted keys to their non-shifted counterparts, used to accurately
48
- * interpret which character a shifted key press represents.
49
- */
50
- shiftMap: Record<string, string | undefined>;
51
- /**
52
- * Maps the representation of keys when combined with the alt key.
53
- */
54
- translate(ev: Key): string;
55
- /**
56
- * Indicates whether the 'meta' or 'ctrl' key is the primary modifier used for commands,
57
- * differing based on the operating system (e.g., 'metaKey' for macOS).
58
- */
59
- modKey?: 'metaKey' | 'ctrlKey';
60
- }
61
- export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
62
- /**
63
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
64
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
65
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
66
- * layout, and an optional capture mode for events.
67
- *
68
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
69
- * key presses as part of the same sequence or a new one.
70
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
71
- * (especially with modifiers) are interpreted.
72
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
73
- * as propagation and default handling based on the `onKey` callback result.
74
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
75
- * stopping event propagation based on handler response.
76
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
77
- * browser actions.
78
- * @return A cleanup function that removes the event listener.
79
- */
80
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
81
- export declare function parseKey(key: string, layout?: KeyboardLayout): Key[];
82
- /**
83
- * Converts a string representing a key combination into a normalized string format.
84
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
85
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
86
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
87
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
88
- * strings are concatenated with spaces and returned as the normalized form. This is useful
89
- * for ensuring consistent representation of key sequences across different keyboard layouts.
90
- */
91
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
92
- 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 c=void 0===n?250:n,y=o.language;let u=[],d=0;r||(r=t.KeyboardLayoutData[y]||t.KeyboardLayoutData["en-US"]);const f=l(r);function K(e){const t=i(e,f);let o=Date.now();if(!t)return;o-d<c?u.push(t):u=[t];const n=u.slice(0);do{if(!1!==a(n.join(" "),u)){e.stopPropagation(),e.preventDefault(),o=0;break}n.shift()}while(n.length);d=o}return e.addEventListener("keydown",K,{capture:s}),()=>e.removeEventListener("keydown",K,{capture:s})},t.parseKey=function(e,t=s()){return c(e,l(t))},t.normalize=function(e,t=s()){const o=l(t);return c(e,o).map((e=>i(e,o))).join(" ")};const o="undefined"!=typeof window?window.navigator:{language:"en-US",platform:"nodejs"},a=/Mac|iPod|iPhone|iPad/,n=/(shift|ctrl|control|alt|option|meta|command|cmd|mod|[^\s+]+)(\s*\+|\s)?/g,r={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc",Space:"space",Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Quote:"'",Backslash:"\\",Apostrophe:"'",Semicolon:";",Comma:",",Period:".",Slash:"/"};function i(e,{translate:t}){const o=e.key;if(!o||"Shift"===o||"Alt"===o||"Meta"===o||"Control"===o||"Dead"===o&&!e.altKey)return"";const a=t(e);let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&(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 c(e,{modKey:t,shiftMap:o}){const a=[];let r,i={ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:"",code:""};for(;r=n.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{const t=o[e];t?(i.key=t,i.shiftKey=!0):i.key=e}"+"!==r[2]&&(a.push(i),i={ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:"",code:""})}return a}function l(e){return{modKey:a.test(o.platform)?"metaKey":"ctrlKey",...e}}t.KeyboardLayoutData={"en-US":{shiftMap:{"?":"/",">":".","<":",",'"':"'",":":";","{":"[","}":"]","|":"\\","~":"`","+":"=",_:"-","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0"},translate:({code:e,key:t})=>r[e]||(e.startsWith("Key")?e.slice(3).toLowerCase():e.startsWith("Digit")?e.slice(5):t.toLowerCase())}}}));
package/index.js DELETED
@@ -1,233 +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
- const TranslateKey = {
37
- ArrowUp: 'up',
38
- ArrowDown: 'down',
39
- ArrowLeft: 'left',
40
- ArrowRight: 'right',
41
- Escape: 'esc',
42
- Space: 'space',
43
- Backquote: '`',
44
- Minus: '-',
45
- Equal: '=',
46
- BracketLeft: '[',
47
- BracketRight: ']',
48
- Quote: "'",
49
- Backslash: '\\',
50
- Apostrophe: "'",
51
- Semicolon: ';',
52
- Comma: ',',
53
- Period: '.',
54
- Slash: '/',
55
- };
56
- exports.KeyboardLayoutData = {
57
- 'en-US': {
58
- shiftMap: SHIFT_MAP,
59
- translate({ code, key }) {
60
- const translated = TranslateKey[code];
61
- if (translated)
62
- return translated;
63
- if (code.startsWith('Key'))
64
- return code.slice(3).toLowerCase();
65
- if (code.startsWith('Digit'))
66
- return code.slice(5);
67
- return key.toLowerCase();
68
- },
69
- },
70
- };
71
- /**
72
- * The `keyboardEventToString` function converts a `Key` object to a string that represents the key combination pressed.
73
- * It checks individual modifier keys (`ctrlKey`, `altKey`, `shiftKey`, and `metaKey`) and constructs a concatenated
74
- * string reflecting these modifiers followed by the translated character key.
75
- *
76
- * Exceptions include when the `key` is 'Shift', 'Alt', 'Meta', 'Control', or 'Dead' without an `altKey`,
77
- * as these are discarded (represented by an empty string). If no modifiers are pressed, it directly returns
78
- * the translated character.
79
- *
80
- * This conversion provides a consistent way to describe key combinations as strings, essential for handling
81
- * and processing keyboard shortcuts or sequences in the application.
82
- */
83
- function keyboardEventToString(ev, { translate }) {
84
- const key = ev.key;
85
- if (!key ||
86
- key === 'Shift' ||
87
- key === 'Alt' ||
88
- key === 'Meta' ||
89
- key === 'Control' ||
90
- (key === 'Dead' && !ev.altKey))
91
- return '';
92
- const ch = translate(ev);
93
- let result;
94
- if (ev.ctrlKey)
95
- result = 'ctrl';
96
- if (ev.altKey)
97
- result = result ? result + '+alt' : 'alt';
98
- if (ev.shiftKey)
99
- result = result ? result + '+shift' : 'shift';
100
- if (ev.metaKey)
101
- result = result ? result + '+meta' : 'meta';
102
- return result ? result + '+' + ch : ch;
103
- }
104
- /**
105
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
106
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
107
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
108
- * layout, and an optional capture mode for events.
109
- *
110
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
111
- * key presses as part of the same sequence or a new one.
112
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
113
- * (especially with modifiers) are interpreted.
114
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
115
- * as propagation and default handling based on the `onKey` callback result.
116
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
117
- * stopping event propagation based on handler response.
118
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
119
- * browser actions.
120
- * @return A cleanup function that removes the event listener.
121
- */
122
- function handleKeyboard({ element, onKey, delay, layout, capture, }) {
123
- const D = delay === undefined ? 250 : delay;
124
- const locale = navigator.language;
125
- let sequence = [];
126
- let lastT = 0;
127
- layout || (layout = exports.KeyboardLayoutData[locale] || exports.KeyboardLayoutData['en-US']);
128
- const newLayout = augmentLayout(layout);
129
- function handler(ev) {
130
- const k = keyboardEventToString(ev, newLayout);
131
- let t = Date.now();
132
- if (!k)
133
- return;
134
- if (t - lastT < D)
135
- sequence.push(k);
136
- else
137
- sequence = [k];
138
- const seq = sequence.slice(0);
139
- do {
140
- if (onKey(seq.join(' '), sequence) !== false) {
141
- ev.stopPropagation();
142
- ev.preventDefault();
143
- t = 0;
144
- break;
145
- }
146
- seq.shift();
147
- } while (seq.length);
148
- lastT = t;
149
- }
150
- element.addEventListener('keydown', handler, { capture });
151
- return () => element.removeEventListener('keydown', handler, { capture });
152
- }
153
- // Retrieves the default `KeyboardLayout` based on the current user's language settings from `navigator.language`.
154
- // Falls back to the 'en-US' layout if the user's specific language is not available in `KeyboardLayoutData`.
155
- // This function helps ensure that the keyboard handling can adapt to the most appropriate layout for the user,
156
- // facilitating the accurate interpretation of key sequences and modifiers according to locale preferences.
157
- function getDefaultLayout() {
158
- return (exports.KeyboardLayoutData[navigator?.language] || exports.KeyboardLayoutData['en-US']);
159
- }
160
- function newKey() {
161
- return {
162
- ctrlKey: false,
163
- shiftKey: false,
164
- metaKey: false,
165
- altKey: false,
166
- key: '',
167
- code: '',
168
- };
169
- }
170
- /**
171
- * This function, `parseKey`, takes a key combination string and splits it into a sequence of `Key` objects.
172
- * It uses regular expressions to identify each part of the key combination, accounting for modifier keys
173
- * like 'shift', 'ctrl', 'alt', 'meta', and 'mod', the latter being dependent on the `modKey` from the
174
- * `KeyboardLayout` (either 'ctrlKey' or 'metaKey' depending on the platform). For non-modifier keys, it
175
- * checks if the `shiftKey` is active and if the key should be shifted using the `shiftMap`. This logic
176
- * ensures the function captures accurate key state details in preparation for further handling like matching
177
- * key sequences in the `handleKeyboard` function.
178
- */
179
- function _parseKey(key, { modKey, shiftMap }) {
180
- const sequence = [];
181
- let match;
182
- let event = newKey();
183
- while ((match = PARSE_KEY.exec(key.toLowerCase()))) {
184
- const ch = match[1];
185
- if (ch === 'shift')
186
- event.shiftKey = true;
187
- else if (ch === 'ctrl' || ch === 'control')
188
- event.ctrlKey = true;
189
- else if (ch === 'alt' || ch === 'option')
190
- event.altKey = true;
191
- else if (ch === 'meta' || ch === 'cmd' || ch === 'command')
192
- event.metaKey = true;
193
- else if (ch === 'mod')
194
- event[modKey] = true;
195
- else {
196
- const shifted = shiftMap[ch];
197
- if (shifted) {
198
- event.key = shifted;
199
- event.shiftKey = true;
200
- }
201
- else
202
- event.key = ch;
203
- }
204
- if (match[2] !== '+') {
205
- sequence.push(event);
206
- event = newKey();
207
- }
208
- }
209
- return sequence;
210
- }
211
- function augmentLayout(layout) {
212
- return {
213
- modKey: IS_MAC.test(navigator.platform) ? 'metaKey' : 'ctrlKey',
214
- ...layout,
215
- };
216
- }
217
- function parseKey(key, layout = getDefaultLayout()) {
218
- return _parseKey(key, augmentLayout(layout));
219
- }
220
- /**
221
- * Converts a string representing a key combination into a normalized string format.
222
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
223
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
224
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
225
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
226
- * strings are concatenated with spaces and returned as the normalized form. This is useful
227
- * for ensuring consistent representation of key sequences across different keyboard layouts.
228
- */
229
- function normalize(key, layout = getDefaultLayout()) {
230
- const newLayout = augmentLayout(layout);
231
- const sequence = _parseKey(key, newLayout);
232
- return sequence.map(key => keyboardEventToString(key, newLayout)).join(' ');
233
- }
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"},TranslateKey={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc",Space:"space",Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Quote:"'",Backslash:"\\",Apostrophe:"'",Semicolon:";",Comma:",",Period:".",Slash:"/"};function keyboardEventToString(e,{translate:t}){const a=e.key;if(!a||"Shift"===a||"Alt"===a||"Meta"===a||"Control"===a||"Dead"===a&&!e.altKey)return"";const o=t(e);let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&(n=n?n+"+shift":"shift"),e.metaKey&&(n=n?n+"+meta":"meta"),n?n+"+"+o:o}function handleKeyboard({element:e,onKey:t,delay:a,layout:o,capture:n}){const r=void 0===a?250:a,s=navigator.language;let i=[],y=0;o||(o=exports.KeyboardLayoutData[s]||exports.KeyboardLayoutData["en-US"]);const l=augmentLayout(o);function u(e){const a=keyboardEventToString(e,l);let o=Date.now();if(!a)return;o-y<r?i.push(a):i=[a];const n=i.slice(0);do{if(!1!==t(n.join(" "),i)){e.stopPropagation(),e.preventDefault(),o=0;break}n.shift()}while(n.length);y=o}return e.addEventListener("keydown",u,{capture:n}),()=>e.removeEventListener("keydown",u,{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:"",code:""}}function _parseKey(e,{modKey:t,shiftMap:a}){const o=[];let n,r=newKey();for(;n=PARSE_KEY.exec(e.toLowerCase());){const e=n[1];if("shift"===e)r.shiftKey=!0;else if("ctrl"===e||"control"===e)r.ctrlKey=!0;else if("alt"===e||"option"===e)r.altKey=!0;else if("meta"===e||"cmd"===e||"command"===e)r.metaKey=!0;else if("mod"===e)r[t]=!0;else{const t=a[e];t?(r.key=t,r.shiftKey=!0):r.key=e}"+"!==n[2]&&(o.push(r),r=newKey())}return o}function augmentLayout(e){return{modKey:IS_MAC.test(navigator.platform)?"metaKey":"ctrlKey",...e}}function parseKey(e,t=getDefaultLayout()){return _parseKey(e,augmentLayout(t))}function normalize(e,t=getDefaultLayout()){const a=augmentLayout(t);return _parseKey(e,a).map((e=>keyboardEventToString(e,a))).join(" ")}exports.KeyboardLayoutData={"en-US":{shiftMap:SHIFT_MAP,translate({code:e,key:t}){const a=TranslateKey[e];return a||(e.startsWith("Key")?e.slice(3).toLowerCase():e.startsWith("Digit")?e.slice(5):t.toLowerCase())}}};
package/mjs/index.d.ts DELETED
@@ -1,91 +0,0 @@
1
- interface Key {
2
- ctrlKey: boolean;
3
- altKey: boolean;
4
- shiftKey: boolean;
5
- metaKey: boolean;
6
- key: string;
7
- code: 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
- /**
42
- * The `KeyboardLayout` interface describes how a keyboard layout should be structured internally.
43
- */
44
- export 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
- * Maps the representation of keys when combined with the alt key.
52
- */
53
- translate(ev: Key): string;
54
- /**
55
- * Indicates whether the 'meta' or 'ctrl' key is the primary modifier used for commands,
56
- * differing based on the operating system (e.g., 'metaKey' for macOS).
57
- */
58
- modKey?: 'metaKey' | 'ctrlKey';
59
- }
60
- export declare const KeyboardLayoutData: Record<string, KeyboardLayout>;
61
- /**
62
- * The `handleKeyboard` function sets up event listeners to handle keyboard events on a given HTML element.
63
- * It accepts a configuration object (`KeyboardOptions`) which includes the target HTML element, a callback
64
- * `onKey` to handle keyboard sequences, a `delay` for typing sequence recognition, an optional keyboard
65
- * layout, and an optional capture mode for events.
66
- *
67
- * - Defaults the delay to 250ms if not specified, using this delay to determine when to treat subsequent
68
- * key presses as part of the same sequence or a new one.
69
- * - Determines the keyboard layout, either from the provided options or defaults, which affects how keys
70
- * (especially with modifiers) are interpreted.
71
- * - Adds a `keydown` event listener to the provided element, allowing modification of event behavior such
72
- * as propagation and default handling based on the `onKey` callback result.
73
- * - Builds a key sequence based on timing and calls the `onKey` handler with the assembled sequence,
74
- * stopping event propagation based on handler response.
75
- * - The handler uses the sequence to manage shortcuts and performs preventative measures against default
76
- * browser actions.
77
- * @return A cleanup function that removes the event listener.
78
- */
79
- export declare function handleKeyboard({ element, onKey, delay, layout, capture, }: KeyboardOptions): () => void;
80
- export declare function parseKey(key: string, layout?: KeyboardLayout): Key[];
81
- /**
82
- * Converts a string representing a key combination into a normalized string format.
83
- * This function takes a `key` string and an optional `layout` object (defaults to the user's layout).
84
- * It uses `parseKey` to break the key combination into individual `Key` objects, each representing
85
- * a parsed key press. It then converts each `Key` object back to a string using `keyboardEventToString`,
86
- * considering the layout's details like `shiftedKeys` and `shiftMap`. The resulting
87
- * strings are concatenated with spaces and returned as the normalized form. This is useful
88
- * for ensuring consistent representation of key sequences across different keyboard layouts.
89
- */
90
- export declare function normalize(key: string, layout?: KeyboardLayout): string;
91
- 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"},TranslateKey={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",Escape:"esc",Space:"space",Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Quote:"'",Backslash:"\\",Apostrophe:"'",Semicolon:";",Comma:",",Period:".",Slash:"/"};export const KeyboardLayoutData={"en-US":{shiftMap:SHIFT_MAP,translate:({code:e,key:t})=>TranslateKey[e]||(e.startsWith("Key")?e.slice(3).toLowerCase():e.startsWith("Digit")?e.slice(5):t.toLowerCase())}};function keyboardEventToString(e,{translate:t}){const a=e.key;if(!a||"Shift"===a||"Alt"===a||"Meta"===a||"Control"===a||"Dead"===a&&!e.altKey)return"";const o=t(e);let n;return e.ctrlKey&&(n="ctrl"),e.altKey&&(n=n?n+"+alt":"alt"),e.shiftKey&&(n=n?n+"+shift":"shift"),e.metaKey&&(n=n?n+"+meta":"meta"),n?n+"+"+o:o}export function handleKeyboard({element:e,onKey:t,delay:a,layout:o,capture:n}){const r=void 0===a?250:a,i=navigator.language;let s=[],y=0;o||(o=KeyboardLayoutData[i]||KeyboardLayoutData["en-US"]);const l=augmentLayout(o);function u(e){const a=keyboardEventToString(e,l);let o=Date.now();if(!a)return;o-y<r?s.push(a):s=[a];const n=s.slice(0);do{if(!1!==t(n.join(" "),s)){e.stopPropagation(),e.preventDefault(),o=0;break}n.shift()}while(n.length);y=o}return e.addEventListener("keydown",u,{capture:n}),()=>e.removeEventListener("keydown",u,{capture:n})}function getDefaultLayout(){return KeyboardLayoutData[navigator?.language]||KeyboardLayoutData["en-US"]}function newKey(){return{ctrlKey:!1,shiftKey:!1,metaKey:!1,altKey:!1,key:"",code:""}}function _parseKey(e,{modKey:t,shiftMap:a}){const o=[];let n,r=newKey();for(;n=PARSE_KEY.exec(e.toLowerCase());){const e=n[1];if("shift"===e)r.shiftKey=!0;else if("ctrl"===e||"control"===e)r.ctrlKey=!0;else if("alt"===e||"option"===e)r.altKey=!0;else if("meta"===e||"cmd"===e||"command"===e)r.metaKey=!0;else if("mod"===e)r[t]=!0;else{const t=a[e];t?(r.key=t,r.shiftKey=!0):r.key=e}"+"!==n[2]&&(o.push(r),r=newKey())}return o}function augmentLayout(e){return{modKey:IS_MAC.test(navigator.platform)?"metaKey":"ctrlKey",...e}}export function parseKey(e,t=getDefaultLayout()){return _parseKey(e,augmentLayout(t))}export function normalize(e,t=getDefaultLayout()){const a=augmentLayout(t);return _parseKey(e,a).map((e=>keyboardEventToString(e,a))).join(" ")}
package/test.d.ts DELETED
@@ -1,2 +0,0 @@
1
- declare const _default: import("@cxl/spec").Test;
2
- export default _default;