-
-
Notifications
You must be signed in to change notification settings - Fork 232
/
test-keyboard.ts
332 lines (285 loc) Β· 7.86 KB
/
test-keyboard.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import { includes, take } from '@remirror/core-helpers';
import {
KeyboardConstructorParams,
KeyboardEventName,
ModifierInformation,
OptionsParams,
OptionsWithTypingParams,
TextInputParams,
TypingInputParams,
} from './test-keyboard-types';
import { cleanKey, createKeyboardEvent, getModifierInformation } from './test-keyboard-utils';
import {
isUSKeyboardCharacter,
noKeyPress,
noKeyUp,
SupportedCharacters,
usKeyboardLayout,
} from './us-keyboard-layout';
export interface BatchedKeyboardAction {
/**
* When called will dispatched the stored event.
*/
dispatch: () => void;
/**
* The event that will be dispatched.
*/
event: KeyboardEvent;
/**
* The type of the event.
*/
type: KeyboardEventName;
}
/**
* The callback function signature for the `eachEvent` which is available when `batch` is true.
*/
export type BatchedCallback = (
action: BatchedKeyboardAction,
index: number,
actions: BatchedKeyboardAction[],
) => void;
export class Keyboard {
public static create(params: KeyboardConstructorParams) {
return new Keyboard(params);
}
static get defaultOptions(): KeyboardEventInit {
return {
bubbles: true,
cancelable: true,
composed: true,
};
}
public status: 'started' | 'ended' | 'idle' = 'idle';
private readonly target: HTMLElement;
private readonly defaultOptions: KeyboardEventInit;
private readonly isMac: boolean;
private readonly batch: boolean;
private readonly onEventDispatch?: (event: KeyboardEvent) => void;
private actions: BatchedKeyboardAction[] = [];
private get started() {
return this.status === 'started';
}
constructor({
target,
defaultOptions = Keyboard.defaultOptions,
isMac = false,
batch = false,
onEventDispatch,
}: KeyboardConstructorParams) {
this.target = target as HTMLElement;
this.defaultOptions = defaultOptions;
this.isMac = isMac;
this.batch = batch;
this.onEventDispatch = onEventDispatch;
}
/**
* Starts the fake timers and sets the keyboard status to 'started'
*/
public start() {
if (this.started) {
return this;
}
this.status = 'started';
return this;
}
/**
* Ends the fake timers and sets the keyboard status to 'ended'
*/
public end() {
if (!this.started) {
return this;
}
if (this.batch) {
this.runBatchedEvents();
this.actions = [];
}
this.status = 'ended';
return this;
}
/**
* When batched is true the user can run through each event and fire as they please.
*/
public forEach(fn: BatchedCallback) {
if (!this.started) {
return this;
}
if (!this.batch) {
throw new Error(`'forEach' is only available when 'batched' is set to 'true'.`);
}
this.actions.forEach(fn);
this.actions = [];
this.status = 'ended';
return this;
}
/**
* Runs all the batched events.
*/
private runBatchedEvents() {
this.actions.forEach(action => {
action.dispatch();
});
}
/**
* Like `this.char` but only supports US Keyboard Characters. This is mainly
* a utility for TypeScript and autocomplete support when typing characters.
*
* @param params - see {@link TextInputParams}
*/
public usChar({
text,
options = Object.create(null),
typing = false,
}: TextInputParams<SupportedCharacters>) {
if (!isUSKeyboardCharacter(text)) {
throw new Error(
'This is not a supported character. For generic characters use the `keyboard.char` method instead',
);
}
return this.char({ text, options, typing });
}
/**
* Dispatches an event for a keyboard character
*
* @param params - see {@link TextInputParams}
*/
public char({ text, options, typing }: TextInputParams) {
options = {
...options,
...(isUSKeyboardCharacter(text) ? cleanKey(text) : { key: text }),
};
this.fireAllEvents({ options, typing });
return this;
}
/**
* Triggers a keydown event with provided options
*
* @param params - see {@link OptionsParams}
*/
public keyDown = ({ options }: OptionsParams) => {
return this.dispatchEvent('keydown', options);
};
/**
* Trigger a keypress event with the provided options
*
* @param params - see {@link OptionsParams}
*/
public keyPress = ({ options }: OptionsParams) => {
return this.dispatchEvent('keypress', options);
};
/**
* Trigger a keyup event with the provided options
*
* @param params - see {@link OptionsParams}
*/
public keyUp = ({ options }: OptionsParams) => {
return this.dispatchEvent('keyup', options);
};
/**
* Breaks a string into single characters and fires a keyboard into the target node
*
* @param params - see {@link TypingInputParams}
*/
public type({ text, options = Object.create(null) }: TypingInputParams) {
for (const char of text) {
this.char({ text: char, options, typing: true });
}
return this;
}
/**
* Enables typing modifier commands
*
* ```ts
* const editor = document.getElementById('editor');
* const keyboard = new Keyboard({ target: editor });
* keyboard
* .mod({text: 'Shift-Meta-A'})
* .end();
* ```
*
* @param params - see {@link TextInputParams}
*/
public mod({ text, options = Object.create(null) }: TextInputParams) {
let modifiers = text.split(/-(?!$)/);
let result = modifiers[modifiers.length - 1];
modifiers = take(modifiers, modifiers.length - 1);
if (result === 'Space') {
result = ' ';
}
const info = getModifierInformation({ modifiers, isMac: this.isMac });
this.fireModifierEvents(info, 'keydown');
this.type({ text: result, options: { ...options, ...info } });
this.fireModifierEvents(info, 'keyup');
return this;
}
/**
* Fires events where valid.
*
* @param options - see {@link OptionsWithTypingParams}
*/
private fireAllEvents({ options, typing = false }: OptionsWithTypingParams) {
this.keyDown({ options });
if (
!includes(noKeyPress, options.key) ||
(typing && isUSKeyboardCharacter(options.key) && usKeyboardLayout[options.key].text)
) {
this.keyPress({ options });
}
if (!includes(noKeyUp, options.key)) {
this.keyUp({ options });
}
return this;
}
/**
* Fires all modifier events
*
* @param info - the modifier information for the keys see {@link ModifierInformation}
* @param type - the keyboard event type
*
*/
private fireModifierEvents(
{ altKey, ctrlKey, metaKey, shiftKey }: ModifierInformation,
type: 'keydown' | 'keyup',
) {
const event = type === 'keydown' ? this.keyDown : this.keyUp;
if (shiftKey) {
event({ options: { ...this.defaultOptions, ...cleanKey('Shift') } });
}
if (metaKey) {
if (this.isMac) {
event({ options: { ...this.defaultOptions, ...cleanKey('Meta') } });
} else {
event({ options: { ...this.defaultOptions, ...cleanKey('Control') } });
}
}
if (ctrlKey) {
event({ options: { ...this.defaultOptions, ...cleanKey('Control') } });
}
if (altKey) {
event({ options: { ...this.defaultOptions, ...cleanKey('Alt') } });
}
}
/**
* Dispatches the action or adds it to the queue when batching is enabled.
*
* @param type - the keyboard event name
* @param options - options passed to the keyboard event. See {@link KeyboardEventInit}
*/
private dispatchEvent(type: KeyboardEventName, options: KeyboardEventInit) {
if (!this.started) {
this.start();
}
const event = createKeyboardEvent(type, { ...this.defaultOptions, ...options });
const dispatch = () => {
this.target.dispatchEvent(event);
if (this.onEventDispatch) {
this.onEventDispatch(event);
}
};
if (this.batch) {
this.actions.push({ dispatch, event, type });
} else {
dispatch();
}
return this;
}
}