New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

ctrl-keys

Package Overview
Dependencies
Maintainers
0
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ctrl-keys - npm Package Compare versions

Comparing version 1.0.6-alpha to 1.0.6

dist/index.d.mts

520

dist/index.d.ts

@@ -1,56 +0,484 @@

import { Join, SubArray, MutableTuple } from "just-types";
declare const modifiers: readonly ["ctrl", "alt", "meta", "shift"];
declare const characters: string[];
declare const aliases: {
readonly space: " ";
readonly plus: "+";
readonly up: "arrowup";
readonly down: "arrowdown";
readonly left: "arrowleft";
readonly right: "arrowright";
readonly esc: "escape";
type ZeroTo10 = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
type ZeroTo100 = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100;
type Minus100ToZero = 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9 | -10 | -11 | -12 | -13 | -14 | -15 | -16 | -17 | -18 | -19 | -20 | -21 | -22 | -23 | -24 | -25 | -26 | -27 | -28 | -29 | -30 | -31 | -32 | -33 | -34 | -35 | -36 | -37 | -38 | -39 | -40 | -41 | -42 | -43 | -44 | -45 | -46 | -47 | -48 | -49 | -50 | -51 | -52 | -53 | -54 | -55 | -56 | -57 | -58 | -59 | -60 | -61 | -62 | -63 | -64 | -65 | -66 | -67 | -68 | -69 | -70 | -71 | -72 | -73 | -74 | -75 | -76 | -77 | -78 | -79 | -80 | -81 | -82 | -83 | -84 | -85 | -86 | -87 | -88 | -89 | -90 | -91 | -92 | -93 | -94 | -95 | -96 | -97 | -98 | -99 | -100;
type Minus100To100 = Minus100ToZero | ZeroTo100;
type PlusOne = {
'-100': -99;
'-99': -98;
'-98': -97;
'-97': -96;
'-96': -95;
'-95': -94;
'-94': -93;
'-93': -92;
'-92': -91;
'-91': -90;
'-90': -89;
'-89': -88;
'-88': -87;
'-87': -86;
'-86': -85;
'-85': -84;
'-84': -83;
'-83': -82;
'-82': -81;
'-81': -80;
'-80': -79;
'-79': -78;
'-78': -77;
'-77': -76;
'-76': -75;
'-75': -74;
'-74': -73;
'-73': -72;
'-72': -71;
'-71': -70;
'-70': -69;
'-69': -68;
'-68': -67;
'-67': -66;
'-66': -65;
'-65': -64;
'-64': -63;
'-63': -62;
'-62': -61;
'-61': -60;
'-60': -59;
'-59': -58;
'-58': -57;
'-57': -56;
'-56': -55;
'-55': -54;
'-54': -53;
'-53': -52;
'-52': -51;
'-51': -50;
'-50': -49;
'-49': -48;
'-48': -47;
'-47': -46;
'-46': -45;
'-45': -44;
'-44': -43;
'-43': -42;
'-42': -41;
'-41': -40;
'-40': -39;
'-39': -38;
'-38': -37;
'-37': -36;
'-36': -35;
'-35': -34;
'-34': -33;
'-33': -32;
'-32': -31;
'-31': -30;
'-30': -29;
'-29': -28;
'-28': -27;
'-27': -26;
'-26': -25;
'-25': -24;
'-24': -23;
'-23': -22;
'-22': -21;
'-21': -20;
'-20': -19;
'-19': -18;
'-18': -17;
'-17': -16;
'-16': -15;
'-15': -14;
'-14': -13;
'-13': -12;
'-12': -11;
'-11': -10;
'-10': -9;
'-9': -8;
'-8': -7;
'-7': -6;
'-6': -5;
'-5': -4;
'-4': -3;
'-3': -2;
'-2': -1;
'-1': 0;
'0': 1;
'1': 2;
'2': 3;
'3': 4;
'4': 5;
'5': 6;
'6': 7;
'7': 8;
'8': 9;
'9': 10;
'10': 11;
'11': 12;
'12': 13;
'13': 14;
'14': 15;
'15': 16;
'16': 17;
'17': 18;
'18': 19;
'19': 20;
'20': 21;
'21': 22;
'22': 23;
'23': 24;
'24': 25;
'25': 26;
'26': 27;
'27': 28;
'28': 29;
'29': 30;
'30': 31;
'31': 32;
'32': 33;
'33': 34;
'34': 35;
'35': 36;
'36': 37;
'37': 38;
'38': 39;
'39': 40;
'40': 41;
'41': 42;
'42': 43;
'43': 44;
'44': 45;
'45': 46;
'46': 47;
'47': 48;
'48': 49;
'49': 50;
'50': 51;
'51': 52;
'52': 53;
'53': 54;
'54': 55;
'55': 56;
'56': 57;
'57': 58;
'58': 59;
'59': 60;
'60': 61;
'61': 62;
'62': 63;
'63': 64;
'64': 65;
'65': 66;
'66': 67;
'67': 68;
'68': 69;
'69': 70;
'70': 71;
'71': 72;
'72': 73;
'73': 74;
'74': 75;
'75': 76;
'76': 77;
'77': 78;
'78': 79;
'79': 80;
'80': 81;
'81': 82;
'82': 83;
'83': 84;
'84': 85;
'85': 86;
'86': 87;
'87': 88;
'88': 89;
'89': 90;
'90': 91;
'91': 92;
'92': 93;
'93': 94;
'94': 95;
'95': 96;
'96': 97;
'97': 98;
'98': 99;
'99': 100;
'100': 101;
};
declare const codes: Record<string, number>;
export type Modifiers = MutableTuple<typeof modifiers>;
export type Codes = typeof codes;
export type KeyValue = typeof characters[number];
export type KeyAliases = Record<string, KeyValue>;
type Optional<A extends any[]> = A | [];
export type ArrayKey<K extends string = KeyValue> = SubArray<Modifiers> | [...Optional<SubArray<Modifiers>>, K];
export type StringKey<KA extends KeyAliases = {}> = Join<ArrayKey<KeyValue | keyof KA>, '+'>;
export type EncodedKey = number;
export type EncodedSequence = number;
export type Callback = (event?: KeyboardEvent) => any;
export type KeyboardEventListener = (event: KeyboardEvent) => any;
export type HandlerState<KA extends KeyAliases = {}> = {
codes: Record<string, EncodedKey>;
aliases: KA;
type MinusOne = {
'-100': -101;
'-99': -100;
'-98': -99;
'-97': -98;
'-96': -97;
'-95': -96;
'-94': -95;
'-93': -94;
'-92': -93;
'-91': -92;
'-90': -91;
'-89': -90;
'-88': -89;
'-87': -88;
'-86': -87;
'-85': -86;
'-84': -85;
'-83': -84;
'-82': -83;
'-81': -82;
'-80': -81;
'-79': -80;
'-78': -79;
'-77': -78;
'-76': -77;
'-75': -76;
'-74': -75;
'-73': -74;
'-72': -73;
'-71': -72;
'-70': -71;
'-69': -70;
'-68': -69;
'-67': -68;
'-66': -67;
'-65': -66;
'-64': -65;
'-63': -64;
'-62': -63;
'-61': -62;
'-60': -61;
'-59': -60;
'-58': -59;
'-57': -58;
'-56': -57;
'-55': -56;
'-54': -55;
'-53': -54;
'-52': -53;
'-51': -52;
'-50': -51;
'-49': -50;
'-48': -49;
'-47': -48;
'-46': -47;
'-45': -46;
'-44': -45;
'-43': -44;
'-42': -43;
'-41': -42;
'-40': -41;
'-39': -40;
'-38': -39;
'-37': -38;
'-36': -37;
'-35': -36;
'-34': -35;
'-33': -34;
'-32': -33;
'-31': -32;
'-30': -31;
'-29': -30;
'-28': -29;
'-27': -28;
'-26': -27;
'-25': -26;
'-24': -25;
'-23': -24;
'-22': -23;
'-21': -22;
'-20': -21;
'-19': -20;
'-18': -19;
'-17': -18;
'-16': -17;
'-15': -16;
'-14': -15;
'-13': -14;
'-12': -13;
'-11': -12;
'-10': -11;
'-9': -10;
'-8': -9;
'-7': -8;
'-6': -7;
'-5': -6;
'-4': -5;
'-3': -4;
'-2': -3;
'-1': -2;
'0': -1;
'1': 0;
'2': 1;
'3': 2;
'4': 3;
'5': 4;
'6': 5;
'7': 6;
'8': 7;
'9': 8;
'10': 9;
'11': 10;
'12': 11;
'13': 12;
'14': 13;
'15': 14;
'16': 15;
'17': 16;
'18': 17;
'19': 18;
'20': 19;
'21': 20;
'22': 21;
'23': 22;
'24': 23;
'25': 24;
'26': 25;
'27': 26;
'28': 27;
'29': 28;
'30': 29;
'31': 30;
'32': 31;
'33': 32;
'34': 33;
'35': 34;
'36': 35;
'37': 36;
'38': 37;
'39': 38;
'40': 39;
'41': 40;
'42': 41;
'43': 42;
'44': 43;
'45': 44;
'46': 45;
'47': 46;
'48': 47;
'49': 48;
'50': 49;
'51': 50;
'52': 51;
'53': 52;
'54': 53;
'55': 54;
'56': 55;
'57': 56;
'58': 57;
'59': 58;
'60': 59;
'61': 60;
'62': 61;
'63': 62;
'64': 63;
'65': 64;
'66': 65;
'67': 66;
'68': 67;
'69': 68;
'70': 69;
'71': 70;
'72': 71;
'73': 72;
'74': 73;
'75': 74;
'76': 75;
'77': 76;
'78': 77;
'79': 78;
'80': 79;
'81': 80;
'82': 81;
'83': 82;
'84': 83;
'85': 84;
'86': 85;
'87': 86;
'88': 87;
'89': 88;
'90': 89;
'91': 90;
'92': 91;
'93': 92;
'94': 93;
'95': 94;
'96': 95;
'97': 96;
'98': 97;
'99': 98;
'100': 99;
};
type Decrement<N extends Minus100To100> = MinusOne[`${N}`];
type Increment<N extends Minus100To100> = PlusOne[`${N}`];
type Range<First extends Minus100To100, Last extends Minus100To100> = First extends Last ? First : Increment<First> extends Last ? First | Last : Increment<Increment<First>> extends Last ? First | Increment<First> | Last : First | Increment<First> | Increment<Increment<First>> | Range<Increment<Increment<Increment<First>>>, Last>;
type Insert<T extends any[] & {
length: ZeroTo100;
}, Item, Index extends number = T['length']> = Index extends 0 ? [Item, ...T] : T extends [infer A, ...infer Rest] ? [A, ...Insert<Rest, Item, Decrement<Index>>] : [
...T,
Item
];
type Literal = string | number | bigint | symbol;
type Join<T extends Literal[], Separator extends Literal> = T extends [infer Head, ...infer Tail] ? Tail extends [] ? `${Head}` : `${Head}${Separator}${Join<Tail, Separator>}` : '';
type InsertAnywhere<T extends any[] & {
length: ZeroTo100;
}, X> = Insert<T, X, Range<0, T['length']>>;
type Permutation<T extends any[] & {
length: ZeroTo10;
}> = T extends [infer A, infer B, infer C, ...infer Rest] ? InsertAnywhere<InsertAnywhere<InsertAnywhere<Permutation<Rest>, A>, B>, C> : T extends [infer A, infer B, ...infer Rest] ? InsertAnywhere<InsertAnywhere<Permutation<Rest>, A>, B> : T extends [infer A, ...infer Rest] ? InsertAnywhere<Permutation<Rest>, A> : [
];
type Slice<T extends any[] & {
length: ZeroTo100;
}, Start extends ZeroTo100, Count extends ZeroTo100 = 100> = Count extends 0 ? [] : T extends [infer Head, ...infer Tail] ? Start extends 0 ? [Head, ...Slice<Tail, 0, Decrement<Count>>] : Slice<Tail, Decrement<Start>, Count> : [];
type SubArray<T extends any[] & {
length: ZeroTo100;
}> = Slice<T, Range<0, T['length']>, Range<0, T['length']>>;
type Modifiers = ['ctrl', 'alt', 'meta', 'shift'];
type Modifier = Modifiers[number];
type AliasCharacter = 'space' | 'plus' | 'up' | 'down' | 'left' | 'right' | 'esc';
type Key = Join<NormalizedKey<Character | AliasCharacter>, '+'>;
type NormalizedKey<C extends string = Character> = SubArray<Permutation<Modifiers>> | [...SubArray<Permutation<Modifiers>>, C];
type EncodedKey = number;
type Sequence = Key[];
type NormalizedSequence = NormalizedKey[];
type EncodedSequence = number;
type KeyboardEventType = 'keydown' | 'keyup';
type Callback = (event?: KeyboardEvent) => any;
type KeyboardEventListener = (event: KeyboardEvent) => any;
type State = {
history: EncodedKey[];
historySize: number;
disabledSequenceCodes: Set<number>;
disabledSequenceCodes: Set<EncodedSequence>;
bindings: Map<EncodedSequence, Set<Callback>>;
};
export interface HandlerInterface<KA extends KeyAliases = {}> {
add(key: StringKey<KA>, fn: Callback): this;
add(keys: Array<StringKey<KA>>, fn: Callback): this;
remove(key: StringKey<KA>, fn: Callback): this;
remove(keys: Array<StringKey<KA>>, fn: Callback): this;
enable(key: StringKey<KA>): this;
enable(keys: Array<StringKey<KA>>): this;
disable(key: StringKey<KA>): this;
disable(keys: Array<StringKey<KA>>): this;
type Binding = [Key, Callback] | [Key, Key, Callback] | [Key, Key, Key, Callback] | [Key, Key, Key, Key, Callback];
interface HandlerInterface {
add(...args: Binding): this;
remove(...args: Binding): this;
enable(...keys: Sequence): this;
disable(...keys: Sequence): this;
handle(event: KeyboardEvent): boolean;
}
declare class Handler<Aliases extends KeyAliases> implements HandlerInterface<Aliases> {
protected state: HandlerState<Aliases>;
constructor(state: HandlerState<Aliases>);
add(keys: StringKey<Aliases> | Array<StringKey<Aliases>>, fn: Callback): this;
remove(keys: StringKey<Aliases> | Array<StringKey<Aliases>>, fn: Callback): this;
enable(keys: StringKey<Aliases> | Array<StringKey<Aliases>>): this;
disable(keys: StringKey<Aliases> | Array<StringKey<Aliases>>): this;
type Character = '_' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | ' ' | '`' | "'" | '"' | '~' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '.' | '-' | '+' | '=' | '[' | ']' | '{' | '}' | '<' | '>' | ',' | '/' | '?' | ';' | ':' | '\\' | '|' | 'capslock' | 'numlock' | 'enter' | 'tab' | 'arrowdown' | 'arrowleft' | 'arrowright' | 'arrowup' | 'end' | 'home' | 'pagedown' | 'pageup' | 'backspace' | 'delete' | 'insert' | 'escape' | 'f1' | 'f2' | 'f3' | 'f4' | 'f5' | 'f6' | 'f7' | 'f8' | 'f9' | 'f10' | 'f11' | 'f12' | 'f13' | 'f14' | 'f15' | 'f16' | 'f17' | 'f18' | 'f19' | 'f20' | 'f21' | 'f22' | 'f23';
declare class Handler implements HandlerInterface {
protected state: State;
constructor(state: State);
add(...args: Binding): this;
remove(...args: Binding): this;
enable(...keys: Sequence): this;
disable(...keys: Sequence): this;
handle(event: KeyboardEvent): boolean;
}
type DefaultAliases = typeof aliases;
export function createHandler<Aliases extends KeyAliases = DefaultAliases>(customAliases?: Aliases): Handler<Aliases>;
//# sourceMappingURL=index.d.ts.map
declare function keys(): Handler;
export { type AliasCharacter, type Binding, type Callback, type Character, type EncodedKey, type EncodedSequence, type HandlerInterface, type Key, type KeyboardEventListener, type KeyboardEventType, type Modifier, type NormalizedKey, type NormalizedSequence, type Sequence, type State, keys as default, keys };

236

dist/index.js

@@ -1,234 +0,2 @@

function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
function $parcel$exportWildcard(dest, source) {
Object.keys(source).forEach(function(key) {
if (key === 'default' || key === '__esModule' || dest.hasOwnProperty(key)) {
return;
}
Object.defineProperty(dest, key, {
enumerable: true,
get: function get() {
return source[key];
}
});
});
return dest;
}
$parcel$export(module.exports, "createHandler", () => $aa45dd47f927307f$export$b28d6921b4a85ec4);
var $2ae344e2615bfe7e$exports = {};
const $5625d0caec0a5724$export$c2f15f629432a51d = [
'ctrl',
'alt',
'meta',
'shift'
];
const $5625d0caec0a5724$export$30a86d91af8ff6e6 = '0_1_2_3_4_5_6_7_8_9_a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z_ _`_\'_"_~_!_@_#_$_%_^_&_*_(_)_._-_+_=_[_]_{_}_<_>_,_/_?_;_:_\\_|_capslock_numlock_enter_tab_arrowdown_arrowleft_arrowright_arrowup_end_home_pagedown_pageup_backspace_delete_insert_escape_f1_f2_f3_f4_f5_f6_f7_f8_f9_f10_f11_f12_f13_f14_f15_f16_f17_f18_f19_f20_f21_f22_f23'.split('_');
$5625d0caec0a5724$export$30a86d91af8ff6e6.push('_');
const $5625d0caec0a5724$export$9af93bb9e9126a2 = {
space: ' ',
plus: '+',
up: 'arrowup',
down: 'arrowdown',
left: 'arrowleft',
right: 'arrowright',
esc: 'escape'
};
const $5625d0caec0a5724$export$e45cb6485273080e = {
};
let $5625d0caec0a5724$var$i = 1;
for (const c of $5625d0caec0a5724$export$30a86d91af8ff6e6)$5625d0caec0a5724$export$e45cb6485273080e[c] = $5625d0caec0a5724$var$i++;
function $7b9247eb6c5b8f85$export$e0c709538cb8ae18(aliases, key) {
let parts;
if (key === '+') return [
'+'
];
if ('+' == key.slice(-1)) {
parts = key.slice(0, -2).split('+');
parts.push('+');
} else parts = key.split('+');
return parts.map((x)=>aliases[x] || x
);
}
function $7b9247eb6c5b8f85$export$b109b10146e8f9ba(aliases, sequence) {
return sequence.map((x)=>$7b9247eb6c5b8f85$export$e0c709538cb8ae18(aliases, x)
);
}
/**
We want to encode keys and sequences of keys as numbers for performance
A key code is 13 bits: XXXXXXXXXCAMS
XXXXXXXXX: 9 bits representing the character (event.key value).
A character can't have a code `0`, that's a special value.
We can have at most 511 different characters!
CAMS: 4 bits representing the modifiers `Ctrl`, `Alt`, `Meta` and `Shift` in this order.
A sequence of keys is represented by the concatenation of codes of the keys.
An integer can safely be represented with 53 bits in Javascript `Number.MAX_SAFE_INTEGER`
Since every key takes 13bits, a sequence can at most contain 4 keys = 52 bits!
*/ const $b0dd6840dedf4baf$var$MODIFIERS_SIZE = 4;
const $b0dd6840dedf4baf$var$CHARACTER_SIZE = 9;
const $b0dd6840dedf4baf$var$KEY_SIZE = $b0dd6840dedf4baf$var$CHARACTER_SIZE + $b0dd6840dedf4baf$var$MODIFIERS_SIZE;
const $b0dd6840dedf4baf$var$MODIFIERS_UPPER_BOUND = 2 ** $b0dd6840dedf4baf$var$MODIFIERS_SIZE;
const $b0dd6840dedf4baf$var$ONE_KEY_UPPER_BOUND = 2 ** $b0dd6840dedf4baf$var$KEY_SIZE;
const $b0dd6840dedf4baf$var$TWO_KEYS_UPPER_BOUND = 2 ** (2 * $b0dd6840dedf4baf$var$KEY_SIZE);
const $b0dd6840dedf4baf$var$THREE_KEYS_UPPER_BOUND = 2 ** (3 * $b0dd6840dedf4baf$var$KEY_SIZE);
function $b0dd6840dedf4baf$export$81dbaac8d5335cb6(codes, event) {
let code = codes[event.key.toLowerCase()] || 0;
for (const modifier of $5625d0caec0a5724$export$c2f15f629432a51d)code = 2 * code + (event[`${modifier}Key`] ? 1 : 0);
return code;
}
function $b0dd6840dedf4baf$export$a0511d6cbab6225d(codes, key) {
const parts = new Set(key);
let code = codes[key[key.length - 1].toLowerCase()] || 0;
for (const modifier of $5625d0caec0a5724$export$c2f15f629432a51d)code = 2 * code + (parts.has(modifier) ? 1 : 0);
return code;
}
function $b0dd6840dedf4baf$export$4cb205243eb10110(codes, sequence) {
if (sequence.length > 4) throw `Can't encode sequence of more than 4 keys!`;
let code = 0;
for (const key of sequence)code = code * $b0dd6840dedf4baf$var$ONE_KEY_UPPER_BOUND + $b0dd6840dedf4baf$export$a0511d6cbab6225d(codes, key);
return code;
}
function $b0dd6840dedf4baf$export$d95305c1c4c40d1d(encodedKey) {
return encodedKey >> $b0dd6840dedf4baf$var$MODIFIERS_SIZE;
}
function $b0dd6840dedf4baf$export$a10907c21fef597b(encodedKey) {
return encodedKey % $b0dd6840dedf4baf$var$MODIFIERS_UPPER_BOUND;
}
function $b0dd6840dedf4baf$export$6199ce3afbf6d7f6(encoded) {
if (encoded < $b0dd6840dedf4baf$var$ONE_KEY_UPPER_BOUND) return 1;
if (encoded < $b0dd6840dedf4baf$var$TWO_KEYS_UPPER_BOUND) return 2;
if (encoded < $b0dd6840dedf4baf$var$THREE_KEYS_UPPER_BOUND) return 3;
return 4;
}
function $b0dd6840dedf4baf$export$ea75b4e9c5008d0c(keys) {
const result = [];
let sequenceCode = 0;
let multiplier = 0;
for(let i = keys.length - 1; i >= 0; i--){
sequenceCode = 2 ** multiplier * keys[i] + sequenceCode;
multiplier = multiplier + 13;
result.push(sequenceCode);
}
return result;
}
function $b32bc79731ce4566$export$2666eec10feb506f(state, sequence, fn) {
const sequenceCode = $b0dd6840dedf4baf$export$4cb205243eb10110(state.codes, $7b9247eb6c5b8f85$export$b109b10146e8f9ba(state.aliases, sequence));
if (!state.bindings.has(sequenceCode)) state.bindings.set(sequenceCode, new Set());
state.bindings.get(sequenceCode).add(fn);
return $b32bc79731ce4566$export$3b88b12a1b2479e8(state);
}
function $b32bc79731ce4566$export$164d2c5f74d5827c(state, sequence, fn) {
const sequenceCode = $b0dd6840dedf4baf$export$4cb205243eb10110(state.codes, $7b9247eb6c5b8f85$export$b109b10146e8f9ba(state.aliases, sequence));
const fns = state.bindings.get(sequenceCode);
if (fns) {
fns.delete(fn);
if (fns.size == 0) state.bindings.delete(sequenceCode);
}
return $b32bc79731ce4566$export$3b88b12a1b2479e8(state);
}
function $b32bc79731ce4566$export$445cc5a591c8a8a2(state, sequence) {
const sequenceCode = $b0dd6840dedf4baf$export$4cb205243eb10110(state.codes, $7b9247eb6c5b8f85$export$b109b10146e8f9ba(state.aliases, sequence));
state.disabledSequenceCodes.delete(sequenceCode);
return state;
}
function $b32bc79731ce4566$export$21b222afdafd214b(state, sequence) {
const sequenceCode = $b0dd6840dedf4baf$export$4cb205243eb10110(state.codes, $7b9247eb6c5b8f85$export$b109b10146e8f9ba(state.aliases, sequence));
state.disabledSequenceCodes.add(sequenceCode);
return state;
}
function $b32bc79731ce4566$export$d6e5ca10785815df(state, event) {
const key = $b0dd6840dedf4baf$export$81dbaac8d5335cb6(state.codes, event);
state.history.push(key);
if (state.history.length > state.historySize) state.history.shift();
let foundMatchingSequence = false;
for (const sequenceCode of $b0dd6840dedf4baf$export$ea75b4e9c5008d0c(state.history)){
if (state.disabledSequenceCodes.has(sequenceCode)) continue;
for (const fn of state.bindings.get(sequenceCode) || []){
foundMatchingSequence = true;
fn(event);
}
}
return [
state,
foundMatchingSequence
];
}
function $b32bc79731ce4566$export$3b88b12a1b2479e8(state) {
state.historySize = 0;
for (const code of state.bindings.keys())state.historySize = Math.max(state.historySize, $b0dd6840dedf4baf$export$6199ce3afbf6d7f6(code));
return state;
}
class $6a5631b959ebf7d3$export$a428cd33b25d5283 {
add(keys, fn) {
if (typeof keys === 'string') keys = [
keys
];
this.state = $b32bc79731ce4566$export$2666eec10feb506f(this.state, keys, fn);
return this;
}
remove(keys, fn) {
if (typeof keys === 'string') keys = [
keys
];
this.state = $b32bc79731ce4566$export$164d2c5f74d5827c(this.state, keys, fn);
return this;
}
enable(keys) {
if (typeof keys === 'string') keys = [
keys
];
this.state = $b32bc79731ce4566$export$445cc5a591c8a8a2(this.state, keys);
return this;
}
disable(keys) {
if (typeof keys === 'string') keys = [
keys
];
this.state = $b32bc79731ce4566$export$21b222afdafd214b(this.state, keys);
return this;
}
handle(event) {
const [state, foundMatchingSequence] = $b32bc79731ce4566$export$d6e5ca10785815df(this.state, event);
this.state = state;
return foundMatchingSequence;
}
constructor(state){
this.state = state;
this.add = this.add.bind(this);
this.remove = this.remove.bind(this);
this.handle = this.handle.bind(this);
}
}
function $aa45dd47f927307f$export$b28d6921b4a85ec4(customAliases) {
return new $6a5631b959ebf7d3$export$a428cd33b25d5283({
codes: $5625d0caec0a5724$export$e45cb6485273080e,
aliases: customAliases || $5625d0caec0a5724$export$9af93bb9e9126a2,
history: [],
historySize: 0,
bindings: new Map(),
disabledSequenceCodes: new Set()
});
}
$parcel$exportWildcard(module.exports, $2ae344e2615bfe7e$exports);
//# sourceMappingURL=index.js.map
"use strict";var _=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},B=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of I(t))!T.call(e,r)&&r!==n&&_(e,r,{get:()=>t[r],enumerable:!(o=P(t,r))||o.enumerable});return e};var D=e=>B(_({},"__esModule",{value:!0}),e);var Z={};U(Z,{default:()=>L,keys:()=>O});module.exports=D(Z);var a=["ctrl","alt","meta","shift"],u="__0_1_2_3_4_5_6_7_8_9_a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z_ _`_'_\"_~_!_@_#_$_%_^_&_*_(_)_._-_+_=_[_]_{_}_<_>_,_/_?_;_:_\\_|_capslock_numlock_enter_tab_arrowdown_arrowleft_arrowright_arrowup_end_home_pagedown_pageup_backspace_delete_insert_escape_f1_f2_f3_f4_f5_f6_f7_f8_f9_f10_f11_f12_f13_f14_f15_f16_f17_f18_f19_f20_f21_f22_f23".split("_");u[1]="_";var i={};for(let[e,t]of u.entries())i[t]=e;var l={space:" ",plus:"+",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",esc:"escape"},d=4,H=9;var p=H+d,y=2**d,h=2**p,E=2**(2*p),K=2**(3*p);function m(e){let t;return e==="+"?["+"]:(e.slice(-1)=="+"?(t=e.slice(0,-2).split("+"),t.push("+")):t=e.split("+"),t.map(n=>l[n]||n))}function x(e){let t=new Set(e),n=i[e[e.length-1].toLowerCase()]||0;for(let o of a)n=2*n+(t.has(o)?1:0);return n}function b(e){return e>>d}function S(e){return e%y}function C(e,t){if(e===void 0||b(e)>0)return!1;let n=S(e),o=S(t);return n===o&&b(t)===0?!1:(n&S(t))===n}function q(e){let t=i[e.key.toLowerCase()]||0;for(let n of a)t=2*t+(e[`${n}Key`]?1:0);return t}function s(e){return e.map(m)}function c(e){if(e.length>4)throw"Can't encode sequence of more than 4 keys!";let t=0;for(let n of e)t=t*h+x(n);return t}function g(e){return e<h?1:e<E?2:e<K?3:4}function z(e){let t=[],n=0,o=0;for(let r=e.length-1;r>=0;r--)n=2**o*e[r]+n,o=o+13,t.push(n);return t}function w(e={}){return{history:[],historySize:0,bindings:new Map,disabledSequenceCodes:new Set,...e}}function M(e,t,n){let o=c(s(t));return e.bindings.has(o)||e.bindings.set(o,new Set),e.bindings.get(o).add(n),N(e)}function k(e,t,n){let o=c(s(t)),r=e.bindings.get(o);return r&&(r.delete(n),r.size==0&&e.bindings.delete(o)),N(e)}function v(e,t){let n=c(s(t));return e.disabledSequenceCodes.delete(n),e}function A(e,t){let n=c(s(t));return e.disabledSequenceCodes.add(n),e}function F(e,t){let n=q(t),o=e.history.at(-1);return C(o,n)&&e.history.pop(),e.history.push(n),e.history.length>e.historySize&&e.history.shift(),e}function Y(e){let t=[];for(let n of z(e.history))e.disabledSequenceCodes.has(n)||t.push(...e.bindings.get(n)||[]);return t}function R(e,t){e=F(e,t);let n=Y(e);for(let o of n)o(t);return[e,n]}function N(e){e.historySize=0;for(let t of e.bindings.keys())e.historySize=Math.max(e.historySize,g(t));return e}var f=class{constructor(t){this.state=t;this.add=this.add.bind(this),this.remove=this.remove.bind(this),this.handle=this.handle.bind(this)}add(...t){let n=t.slice(0,-1),o=t.at(-1);return this.state=M(this.state,n,o),this}remove(...t){let n=t.slice(0,-1),o=t.at(-1);return this.state=k(this.state,n,o),this}enable(...t){return this.state=v(this.state,t),this}disable(...t){return this.state=A(this.state,t),this}handle(t){let[n,o]=R(this.state,t);return this.state=n,o.length>0}};function O(){return new f(w())}var L=O;0&&(module.exports={keys});
//# sourceMappingURL=index.js.map
{
"name": "ctrl-keys",
"version": "1.0.6",
"author": "Amine Ben hammou",
"description": "A Typescript library to handle keybindings efficiently.",
"description": "A tiny, super fast, typescript library to handle keybindings efficiently.",
"keywords": [
"typescript",
"keybindings",
"keyboard-shortcuts",
"keyboard-events"
],
"license": "MIT",
"version": "1.0.6-alpha",
"source": "src/index.ts",

@@ -11,3 +17,10 @@ "main": "dist/index.js",

"types": "dist/index.d.ts",
"optimize": true,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"default": "./dist/index.js"
}
},
"files": [

@@ -20,21 +33,19 @@ "dist"

"scripts": {
"build": "parcel build",
"bench": "cd benchmark && yarn && yarn build",
"build": "tsup",
"test": "jest",
"test-coverage": "jest --coverage"
},
"dependencies": {
"just-types": "^1.1.0"
},
"devDependencies": {
"@parcel/packager-ts": "^2.2.1",
"@parcel/transformer-typescript-types": "^2.2.1",
"@testing-library/dom": "^8.11.3",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.0",
"jest": "^27.4.7",
"parcel": "^2.2.1",
"ts-jest": "^27.1.3",
"tslib": "^2.3.1",
"typescript": "^4.5.5"
"@testing-library/dom": "^10.4.0",
"@testing-library/user-event": "^14.6.1",
"@types/jest": "^29.5.14",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"just-types": "^2.0.0-alpha.3",
"ts-jest": "^29.2.5",
"tslib": "^2.8.1",
"tsup": "8.0.1",
"typescript": "^5.7.3"
}
}
# ctrl-keys
A Typescript library to handle keybindings efficiently.
A tiny, super fast, typescript library to handle keybindings efficiently.
[![Bundle size](https://img.shields.io/bundlephobia/minzip/ctrl-keys?style=flat-square)](https://bundlephobia.com/result?p=ctrl-keys)
[![Tests Status](https://img.shields.io/github/workflow/status/webneat/ctrl-keys/Tests?style=flat-square)](https://github.com/webneat/ctrl-keys/actions?query=workflow:"Tests")
[![Tests Status](https://img.shields.io/github/actions/workflow/status/webneat/ctrl-keys/tests.yml?branch=main&style=flat-square)](https://github.com/webneat/ctrl-keys/actions?query=workflow:"Tests")
[![Coverage Status](https://img.shields.io/coveralls/github/webNeat/ctrl-keys/master?style=flat-square)](https://coveralls.io/github/webNeat/ctrl-keys?branch=master)
[![Code Quality](https://img.shields.io/lgtm/grade/javascript/github/webNeat/ctrl-keys?style=flat-square)](https://lgtm.com/projects/g/webNeat/ctrl-keys/context:javascript)
[![Rank](https://img.shields.io/librariesio/sourcerank/npm/ctrl-keys?style=flat-square)](https://libraries.io/npm/ctrl-keys)
[![Version](https://img.shields.io/npm/v/ctrl-keys?style=flat-square)](https://www.npmjs.com/package/ctrl-keys)
[![MIT](https://img.shields.io/npm/l/ctrl-keys?style=flat-square)](LICENSE)
# Contents
- [Features](#features)
- [Installation](#installation)
- [Simple usage in 3 steps](#simple-usage-in-3-steps)
- [Exploring the `ctrl-keys` API](#exploring-the-ctrl-keys-api)
- [Defining keybindings](#defining-keybindings)
- [Adding new keybindings](#adding-new-keybindings)
- [Removing keybindings](#removing-keybindings)
- [Disabling and enabling keybindings](#disabling-and-enabling-keybindings)
- [Handling keyboard events](#handling-keyboard-events)
- [Comparaison with other keybindings libraries](#comparaison-with-other-keybindings-libraries)
- [Changelog](#changelog)
# Features
- Zero code dependencies (Uses [`just-types`](https://github.com/webNeat/just-types) for types).
- Small bundle size **< 2kb**.
- Super fast performance ([see benchmark](#performance-comparaison)).
- Fully typed, offers autocomplete for keybindings.
- Handles multi-keys sequences like `ctrl+k ctrl+b` (Inspired by [vscode keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_keyboard-rules)).
- Does not add global listeners to the `window`, instead it lets you create multiple handlers and bind them to any DOM elements.
- Dynamically add, remove, enable, and disable keybindings.
# Installation
You can install it using `npm` or `yarn`
```bash
npm i ctrl-keys
// or
yarn add ctrl-keys
```
Or use it directly on modern browsers
```html
<script type="module">
import keys from 'https://unpkg.com/ctrl-keys/dist/index.mjs'
// ...
</script>
```
_if you need to use this library on an old browser that doesn't support es modules, please open an issue and I will add a CDN that works for you_
# Simple usage in 3 steps
```ts
import keys from 'ctrl-keys'
// 1. Create a keybindings handler
const handler = keys()
// 2. Add keybindings
handler
.add('ctrl+up', () => {
// do something
})
.add('ctrl+shift+space', 'ctrl+shift+c', () => {
// do something else ...
})
// 3. Handle events
window.addEventListener('keydown', handler.handle)
```
That's it. Now:
- Whenever the `ctrl` and `up` keys are pressed at the same time; the first function will be called.
- Whenever `ctrl`, `shift` and `space` keys are pressed then right after `ctrl`, `shift` and `c` are pressed; the second function will be called.
Let's explore what `ctrl-keys` has to offer in more details in the next section.
# Exploring the `ctrl-keys` API
The default export of `ctrl-keys` is a function that takes no argument and returns a new keybindings handler:
```ts
function keys(): Handler
```
The handler has the following interface
```ts
interface HandlerInterface {
add(...keys: Keys, fn: Callback): this
remove(...keys: Keys, fn: Callback): this
enable(...keys: Keys): this
disable(...keys: Keys): this
handle(event: KeyboardEvent): boolean
}
```
- `add` method binds some `keys` to a function `fn` so that whenever the keys are pressed on the keyboard, that function is called.
- `remove` removes the binding of `keys` to the function `fn`.
- `disable` can be used to temporary disable some keys (not trigger the functions associated to them) and `enable` is used to enable them again.
- `handle` handles a `KeyboardEvent` (the event emitted by `keydown` for example).
We will take a deeper look to each one of these methods bellow. But first, let's see what values can we give as `keys`.
## Defining keybindings
The methods `add`, `remove`, `enable` and `disable` can take **from 1 to 4** `keys`.
A key is represented by a string in the following format `{modifiers}+{character}` where:
- `modifiers` is any combination of the modifiers `ctrl`, `alt`, `shift` and `meta` separated by `+`.
- Examples: `ctrl+alt`, `shift`, `alt+meta`, `ctrl+alt+meta`.
- And `character` is one of:
- `a`, `b`, ..., `z`
- `0`, `1`, ..., `9`
- `'`, `"`, `~`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `.`, `-`, `_`, `+`, `=`, `[`, `]`, `{`, `}`, `<`, `>`, `,`, `/`, `?`, `;`, `:`, `\`, `|`
- `f1`, `f2`, ..., `f23`
- `space`, `enter`, `tab`, `down`, `left`, `right`, `up`, `end`, `capslock`, `numlock`, `home`, `pagedown`, `pageup`, `backspace`, `delete`, `insert`, `escape`
if you are using Typescript, it will offer autocomplete and help you detect typos when writing keys.
![Typescript Autocomplete](https://raw.githubusercontent.com/webNeat/ctrl-keys/main/screenshots/keys-autocomplete.gif)
## Adding new keybindings
The `add` method lets you add new keybindings to the handler, you do that by specifying the keys that will be pressed and the function to call when they are pressed.
```ts
const handler = keys()
.add('ctrl+up', fn1) // add single key binding
.add('ctrl+left', 'ctrl+up', 'ctrl+right', fn2) // add multi keys binding
.add('tab', event => {
// You can access the keyboard event inside the callbacks
})
```
You can add multiple functions to the same key
```ts
handler.add('ctrl+enter', fn1)
handler.add('ctrl+enter', fn2)
handler.add('ctrl+enter', fn3)
handler.add('ctrl+enter', fn2)
```
All added functions will be called (in the same order by which they were added) when handling keyboard events that match the given keys. Adding the same function to the same keys mutiple times will only add it once (the `fn2` in the example above will only be called once when `ctrl+enter` is pressed).
## Removing keybindings
The `remove` method does the opposite of `add`, it by removing keybindings from the handler.
```ts
const handler = keys()
.add('ctrl+a', fn1)
.add('ctrl+b', fn2)
.add('ctrl+a', fn3)
// 'ctrl+a' calls `fn1` and `fn3`
// 'ctrl+b' calls `fn2`
handler.remove('ctrl+b', fn2) // now 'ctrl+b' does nothing
handler.remove('ctrl+a', fn1) // now 'ctrl+a' only calls `fn3`
handler.remove('ctrl+a', fn1) // does nothing because `fn1` is not bound to 'ctrl+a'
```
## Disabling and enabling keybindings
The `disable` and `enable` methods let you disable/enable keybindings.
```ts
const handler = keys()
.add('ctrl+a', fn1)
.add('ctrl+b', fn2)
.add('ctrl+a', fn3)
// 'ctrl+a' calls `fn1` and `fn3`
// 'ctrl+b' calls `fn2`
handler.disable('ctrl+a') // now 'ctrl+a' does nothing
// ...
handler.enable('ctrl+a') // now 'ctrl+a' calls `fn1` and `fn3`
```
**Example use case**
```ts
const handler = keys()
.add('ctrl+a', fn1)
.add('ctrl+a', fn2)
.add('ctrl+a', fn3)
window.addEventListener('keydown', handler.handle)
```
This code will run `fn1`, `fn2` and `fn3` whenever `ctrl+a` is pressed. So if the user is typing into a textarea and presses `ctrl+a` to select all text the functions will be called which may not be the behavior we want. In that case, we can use `disable` to disable all `ctrl+a` bindings when the user starts focuses an input or textarea, and use `enable` to enable them again when the user removes focus from the input.
## Handling keyboard events
`ctrl-keys` does not add listeners to `window` automatically, instead it lets you decide where and when to handle keyboard events. So after creating a handler and adding keybindings to it, you need to use its `handle` method to actually handle keyboard events
```ts
window.addEventListener('keydown', event => {
handler.handle(event)
})
```
**Note** `event.key` is used when matching events against keybindings.
# Comparaison with other keybindings libraries
Before creating this library, I looked around for existing libraries and found some good ones, but none of them provided everything I wanted.
## Some features comparaison
| | ctrl-keys | [tinykeys](https://github.com/jamiebuilds/tinykeys) | [hotkeys](https://github.com/jaywcjlove/hotkeys) | [shortcuts](https://github.com/fabiospampinato/shortcuts) |
| --- | --- | --- | --- | --- |
| Bundle size | 1.23 kB | 0.72 kB | 2.5 kB | 4.4 kB |
| Support for multiple keys sequences | ✅ (up to 4 keys) | ✅ | ❌ | ✅ |
| Dynamically add/remove keybindings | ✅ | ❌ | ✅ | ✅ |
| Gives handler instead of adding listener to `window` | ✅ | ✅ | ❌ | ❌ |
| Typescript autocomplete for keybindings | ✅ | ❌ | ❌ | ❌ |
## Performance comparaison
<table><tr><th>library</th><th>duration</th><th>memory usage</th></tr><tr><td>ctrl-keys</td><td>55 ms</td><td>4711 kb</td></tr><tr><td>shortcuts</td><td>58 ms</td><td>4963 kb</td></tr><tr><td>tinykeys</td><td>69 ms</td><td>5056 kb</td></tr></table>
The results above are of a benchmark of handling a 3 keys sequence 1000 times. [Click here for details](https://github.com/webNeat/ctrl-keys/tree/main/benchmark)
# Changelog
**1.0.6 (January 31th 2025)**
- Add named export to avoid default export issues with CommonJS.
- Replaced `parcel` with `tsup`.
**1.0.5 (January 31th 2025)**
- Fix issue of 2 defautl exports.
**1.0.4 (January 30th 2025)**
- Update dev dependencies.
- Add `module.exports` to enable `require`ing the default export.
**1.0.3 (June 23th 2024)**
- Update dev dependencies.
- Add `exports` to package.json to fix [issue](https://github.com/webNeat/ctrl-keys/issues/8).
**1.0.2 (May 1st 2024)**
- Update dev dependencies.
- Remove `just-types` from dependencies and bundle it in the types declaration istead.
**1.0.1 (June 30th 2023)**
- Update dev dependencies and benchmark.
- Fix Typescript types.
**1.0.0 (March 17th 2022)**
- First release.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc