@testing-library/user-event 12.2.1 → 12.2.2

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/dist/type.js ADDED
@@ -0,0 +1,717 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.type = type;
7
+
8
+ var _dom = require("@testing-library/dom");
9
+
10
+ var _utils = require("./utils");
11
+
12
+ var _click = require("./click");
13
+
14
+ var _navigationKey = require("./keys/navigation-key");
15
+
16
+ // TODO: wrap in asyncWrapper
17
+ const modifierCallbackMap = { ...createModifierCallbackEntries({
18
+ name: 'shift',
19
+ key: 'Shift',
20
+ keyCode: 16,
21
+ modifierProperty: 'shiftKey'
22
+ }),
23
+ ...createModifierCallbackEntries({
24
+ name: 'ctrl',
25
+ key: 'Control',
26
+ keyCode: 17,
27
+ modifierProperty: 'ctrlKey'
28
+ }),
29
+ ...createModifierCallbackEntries({
30
+ name: 'alt',
31
+ key: 'Alt',
32
+ keyCode: 18,
33
+ modifierProperty: 'altKey'
34
+ }),
35
+ ...createModifierCallbackEntries({
36
+ name: 'meta',
37
+ key: 'Meta',
38
+ keyCode: 93,
39
+ modifierProperty: 'metaKey'
40
+ })
41
+ };
42
+ const specialCharCallbackMap = {
43
+ '{arrowleft}': (0, _navigationKey.navigationKey)('ArrowLeft'),
44
+ '{arrowright}': (0, _navigationKey.navigationKey)('ArrowRight'),
45
+ '{enter}': handleEnter,
46
+ '{esc}': handleEsc,
47
+ '{del}': handleDel,
48
+ '{backspace}': handleBackspace,
49
+ '{selectall}': handleSelectall,
50
+ '{space}': handleSpace,
51
+ ' ': handleSpace
52
+ };
53
+
54
+ function wait(time) {
55
+ return new Promise(resolve => setTimeout(() => resolve(), time));
56
+ } // this needs to be wrapped in the event/asyncWrapper for React's act and angular's change detection
57
+ // depending on whether it will be async.
58
+
59
+
60
+ async function type(element, text, {
61
+ delay = 0,
62
+ ...options
63
+ } = {}) {
64
+ // we do not want to wrap in the asyncWrapper if we're not
65
+ // going to actually be doing anything async, so we only wrap
66
+ // if the delay is greater than 0
67
+ let result;
68
+
69
+ if (delay > 0) {
70
+ await (0, _dom.getConfig)().asyncWrapper(async () => {
71
+ result = await typeImpl(element, text, {
72
+ delay,
73
+ ...options
74
+ });
75
+ });
76
+ } else {
77
+ result = typeImpl(element, text, {
78
+ delay,
79
+ ...options
80
+ });
81
+ }
82
+
83
+ return result;
84
+ }
85
+
86
+ async function typeImpl(element, text, {
87
+ delay,
88
+ skipClick = false,
89
+ skipAutoClose = false,
90
+ initialSelectionStart,
91
+ initialSelectionEnd
92
+ }) {
93
+ if (element.disabled) return;
94
+ if (!skipClick) (0, _click.click)(element);
95
+
96
+ if ((0, _utils.isContentEditable)(element) && document.getSelection().rangeCount === 0) {
97
+ const range = document.createRange();
98
+ range.setStart(element, 0);
99
+ range.setEnd(element, 0);
100
+ document.getSelection().addRange(range);
101
+ } // The focused element could change between each event, so get the currently active element each time
102
+
103
+
104
+ const currentElement = () => (0, _utils.getActiveElement)(element.ownerDocument); // by default, a new element has it's selection start and end at 0
105
+ // but most of the time when people call "type", they expect it to type
106
+ // at the end of the current input value. So, if the selection start
107
+ // and end are both the default of 0, then we'll go ahead and change
108
+ // them to the length of the current value.
109
+ // the only time it would make sense to pass the initialSelectionStart or
110
+ // initialSelectionEnd is if you have an input with a value and want to
111
+ // explicitely start typing with the cursor at 0. Not super common.
112
+
113
+
114
+ const value = (0, _utils.getValue)(currentElement());
115
+ const {
116
+ selectionStart,
117
+ selectionEnd
118
+ } = (0, _utils.getSelectionRange)(element);
119
+
120
+ if (value != null && selectionStart === 0 && selectionEnd === 0) {
121
+ (0, _utils.setSelectionRangeIfNecessary)(currentElement(), initialSelectionStart != null ? initialSelectionStart : value.length, initialSelectionEnd != null ? initialSelectionEnd : value.length);
122
+ }
123
+
124
+ const eventCallbacks = function () {
125
+ const callbacks = [];
126
+ let remainingString = text;
127
+
128
+ while (remainingString) {
129
+ const {
130
+ callback,
131
+ remainingString: newRemainingString
132
+ } = getNextCallback(remainingString, skipAutoClose);
133
+ callbacks.push(callback);
134
+ remainingString = newRemainingString;
135
+ }
136
+
137
+ return callbacks;
138
+ }();
139
+
140
+ await async function (callbacks) {
141
+ const eventOverrides = {};
142
+ let prevWasMinus, prevWasPeriod, prevValue, typedValue;
143
+
144
+ for (const callback of callbacks) {
145
+ if (delay > 0) await wait(delay);
146
+
147
+ if (!currentElement().disabled) {
148
+ const returnValue = callback({
149
+ currentElement,
150
+ prevWasMinus,
151
+ prevWasPeriod,
152
+ prevValue,
153
+ eventOverrides,
154
+ typedValue
155
+ });
156
+ Object.assign(eventOverrides, returnValue == null ? void 0 : returnValue.eventOverrides);
157
+ prevWasMinus = returnValue == null ? void 0 : returnValue.prevWasMinus;
158
+ prevWasPeriod = returnValue == null ? void 0 : returnValue.prevWasPeriod;
159
+ prevValue = returnValue == null ? void 0 : returnValue.prevValue;
160
+ typedValue = returnValue == null ? void 0 : returnValue.typedValue;
161
+ }
162
+ }
163
+ }(eventCallbacks);
164
+ }
165
+
166
+ function getNextCallback(remainingString, skipAutoClose) {
167
+ const modifierCallback = getModifierCallback(remainingString, skipAutoClose);
168
+
169
+ if (modifierCallback) {
170
+ return modifierCallback;
171
+ }
172
+
173
+ const specialCharCallback = getSpecialCharCallback(remainingString);
174
+
175
+ if (specialCharCallback) {
176
+ return specialCharCallback;
177
+ }
178
+
179
+ return getTypeCallback(remainingString);
180
+ }
181
+
182
+ function getModifierCallback(remainingString, skipAutoClose) {
183
+ const modifierKey = Object.keys(modifierCallbackMap).find(key => remainingString.startsWith(key));
184
+
185
+ if (!modifierKey) {
186
+ return null;
187
+ }
188
+
189
+ const callback = modifierCallbackMap[modifierKey]; // if this modifier has an associated "close" callback and the developer
190
+ // doesn't close it themselves, then we close it for them automatically
191
+ // Effectively if they send in: '{alt}a' then we type: '{alt}a{/alt}'
192
+
193
+ if (!skipAutoClose && callback.closeName && !remainingString.includes(callback.closeName)) {
194
+ remainingString += callback.closeName;
195
+ }
196
+
197
+ remainingString = remainingString.slice(modifierKey.length);
198
+ return {
199
+ callback,
200
+ remainingString
201
+ };
202
+ }
203
+
204
+ function getSpecialCharCallback(remainingString) {
205
+ const specialChar = Object.keys(specialCharCallbackMap).find(key => remainingString.startsWith(key));
206
+
207
+ if (!specialChar) {
208
+ return null;
209
+ }
210
+
211
+ return {
212
+ callback: specialCharCallbackMap[specialChar],
213
+ remainingString: remainingString.slice(specialChar.length)
214
+ };
215
+ }
216
+
217
+ function getTypeCallback(remainingString) {
218
+ const character = remainingString[0];
219
+ return {
220
+ callback: context => typeCharacter(character, context),
221
+ remainingString: remainingString.slice(1)
222
+ };
223
+ }
224
+
225
+ function setSelectionRange({
226
+ currentElement,
227
+ newValue,
228
+ newSelectionStart
229
+ }) {
230
+ // if we *can* change the selection start, then we will if the new value
231
+ // is the same as the current value (so it wasn't programatically changed
232
+ // when the fireEvent.input was triggered).
233
+ // The reason we have to do this at all is because it actually *is*
234
+ // programmatically changed by fireEvent.input, so we have to simulate the
235
+ // browser's default behavior
236
+ const value = (0, _utils.getValue)(currentElement());
237
+
238
+ if (value === newValue) {
239
+ (0, _utils.setSelectionRangeIfNecessary)(currentElement(), newSelectionStart, newSelectionStart);
240
+ } else {
241
+ // If the currentValue is different than the expected newValue and we *can*
242
+ // change the selection range, than we should set it to the length of the
243
+ // currentValue to ensure that the browser behavior is mimicked.
244
+ (0, _utils.setSelectionRangeIfNecessary)(currentElement(), value.length, value.length);
245
+ }
246
+ }
247
+
248
+ function fireInputEventIfNeeded({
249
+ currentElement,
250
+ newValue,
251
+ newSelectionStart,
252
+ eventOverrides
253
+ }) {
254
+ const prevValue = (0, _utils.getValue)(currentElement());
255
+
256
+ if (!currentElement().readOnly && !(0, _utils.isClickable)(currentElement()) && newValue !== prevValue) {
257
+ if ((0, _utils.isContentEditable)(currentElement())) {
258
+ _dom.fireEvent.input(currentElement(), {
259
+ target: {
260
+ textContent: newValue
261
+ },
262
+ ...eventOverrides
263
+ });
264
+ } else {
265
+ _dom.fireEvent.input(currentElement(), {
266
+ target: {
267
+ value: newValue
268
+ },
269
+ ...eventOverrides
270
+ });
271
+ }
272
+
273
+ setSelectionRange({
274
+ currentElement,
275
+ newValue,
276
+ newSelectionStart
277
+ });
278
+ }
279
+
280
+ return {
281
+ prevValue
282
+ };
283
+ }
284
+
285
+ function typeCharacter(char, {
286
+ currentElement,
287
+ prevWasMinus = false,
288
+ prevWasPeriod = false,
289
+ prevValue = '',
290
+ typedValue = '',
291
+ eventOverrides
292
+ }) {
293
+ const key = char; // TODO: check if this also valid for characters with diacritic markers e.g. úé etc
294
+
295
+ const keyCode = char.charCodeAt(0);
296
+ let nextPrevWasMinus, nextPrevWasPeriod;
297
+ const textToBeTyped = typedValue + char;
298
+
299
+ const keyDownDefaultNotPrevented = _dom.fireEvent.keyDown(currentElement(), {
300
+ key,
301
+ keyCode,
302
+ which: keyCode,
303
+ ...eventOverrides
304
+ });
305
+
306
+ if (keyDownDefaultNotPrevented) {
307
+ const keyPressDefaultNotPrevented = _dom.fireEvent.keyPress(currentElement(), {
308
+ key,
309
+ keyCode,
310
+ charCode: keyCode,
311
+ ...eventOverrides
312
+ });
313
+
314
+ if ((0, _utils.getValue)(currentElement()) != null && keyPressDefaultNotPrevented) {
315
+ let newEntry = char;
316
+
317
+ if (prevWasMinus) {
318
+ newEntry = `-${char}`;
319
+ } else if (prevWasPeriod) {
320
+ newEntry = `${prevValue}.${char}`;
321
+ }
322
+
323
+ if ((0, _utils.isValidDateValue)(currentElement(), textToBeTyped)) {
324
+ newEntry = textToBeTyped;
325
+ }
326
+
327
+ const inputEvent = fireInputEventIfNeeded({ ...(0, _utils.calculateNewValue)(newEntry, currentElement()),
328
+ eventOverrides: {
329
+ data: key,
330
+ inputType: 'insertText',
331
+ ...eventOverrides
332
+ },
333
+ currentElement
334
+ });
335
+ prevValue = inputEvent.prevValue;
336
+
337
+ if ((0, _utils.isValidDateValue)(currentElement(), textToBeTyped)) {
338
+ _dom.fireEvent.change(currentElement(), {
339
+ target: {
340
+ value: textToBeTyped
341
+ }
342
+ });
343
+ } // typing "-" into a number input will not actually update the value
344
+ // so for the next character we type, the value should be set to
345
+ // `-${newEntry}`
346
+ // we also preserve the prevWasMinus when the value is unchanged due
347
+ // to typing an invalid character (typing "-a3" results in "-3")
348
+ // same applies for the decimal character.
349
+
350
+
351
+ if (currentElement().type === 'number') {
352
+ const newValue = (0, _utils.getValue)(currentElement());
353
+
354
+ if (newValue === prevValue && newEntry !== '-') {
355
+ nextPrevWasMinus = prevWasMinus;
356
+ } else {
357
+ nextPrevWasMinus = newEntry === '-';
358
+ }
359
+
360
+ if (newValue === prevValue && newEntry !== '.') {
361
+ nextPrevWasPeriod = prevWasPeriod;
362
+ } else {
363
+ nextPrevWasPeriod = newEntry === '.';
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ _dom.fireEvent.keyUp(currentElement(), {
370
+ key,
371
+ keyCode,
372
+ which: keyCode,
373
+ ...eventOverrides
374
+ });
375
+
376
+ return {
377
+ prevWasMinus: nextPrevWasMinus,
378
+ prevWasPeriod: nextPrevWasPeriod,
379
+ prevValue,
380
+ typedValue: textToBeTyped
381
+ };
382
+ } // yes, calculateNewBackspaceValue and calculateNewValue look extremely similar
383
+ // and you may be tempted to create a shared abstraction.
384
+ // If you, brave soul, decide to so endevor, please increment this count
385
+ // when you inevitably fail: 1
386
+
387
+
388
+ function calculateNewBackspaceValue(element) {
389
+ const {
390
+ selectionStart,
391
+ selectionEnd
392
+ } = (0, _utils.getSelectionRange)(element);
393
+ const value = (0, _utils.getValue)(element);
394
+ let newValue, newSelectionStart;
395
+
396
+ if (selectionStart === null) {
397
+ // at the end of an input type that does not support selection ranges
398
+ // https://github.com/testing-library/user-event/issues/316#issuecomment-639744793
399
+ newValue = value.slice(0, value.length - 1);
400
+ newSelectionStart = selectionStart - 1;
401
+ } else if (selectionStart === selectionEnd) {
402
+ if (selectionStart === 0) {
403
+ // at the beginning of the input
404
+ newValue = value;
405
+ newSelectionStart = selectionStart;
406
+ } else if (selectionStart === value.length) {
407
+ // at the end of the input
408
+ newValue = value.slice(0, value.length - 1);
409
+ newSelectionStart = selectionStart - 1;
410
+ } else {
411
+ // in the middle of the input
412
+ newValue = value.slice(0, selectionStart - 1) + value.slice(selectionEnd);
413
+ newSelectionStart = selectionStart - 1;
414
+ }
415
+ } else {
416
+ // we have something selected
417
+ const firstPart = value.slice(0, selectionStart);
418
+ newValue = firstPart + value.slice(selectionEnd);
419
+ newSelectionStart = firstPart.length;
420
+ }
421
+
422
+ return {
423
+ newValue,
424
+ newSelectionStart
425
+ };
426
+ }
427
+
428
+ function calculateNewDeleteValue(element) {
429
+ const {
430
+ selectionStart,
431
+ selectionEnd
432
+ } = (0, _utils.getSelectionRange)(element);
433
+ const value = (0, _utils.getValue)(element);
434
+ let newValue;
435
+
436
+ if (selectionStart === null) {
437
+ // at the end of an input type that does not support selection ranges
438
+ // https://github.com/testing-library/user-event/issues/316#issuecomment-639744793
439
+ newValue = value;
440
+ } else if (selectionStart === selectionEnd) {
441
+ if (selectionStart === 0) {
442
+ // at the beginning of the input
443
+ newValue = value.slice(1);
444
+ } else if (selectionStart === value.length) {
445
+ // at the end of the input
446
+ newValue = value;
447
+ } else {
448
+ // in the middle of the input
449
+ newValue = value.slice(0, selectionStart) + value.slice(selectionEnd + 1);
450
+ }
451
+ } else {
452
+ // we have something selected
453
+ const firstPart = value.slice(0, selectionStart);
454
+ newValue = firstPart + value.slice(selectionEnd);
455
+ }
456
+
457
+ return {
458
+ newValue,
459
+ newSelectionStart: selectionStart
460
+ };
461
+ }
462
+
463
+ function createModifierCallbackEntries({
464
+ name,
465
+ key,
466
+ keyCode,
467
+ modifierProperty
468
+ }) {
469
+ const closeName = `{/${name}}`;
470
+
471
+ function open({
472
+ currentElement,
473
+ eventOverrides
474
+ }) {
475
+ const newEventOverrides = {
476
+ [modifierProperty]: true
477
+ };
478
+
479
+ _dom.fireEvent.keyDown(currentElement(), {
480
+ key,
481
+ keyCode,
482
+ which: keyCode,
483
+ ...eventOverrides,
484
+ ...newEventOverrides
485
+ });
486
+
487
+ return {
488
+ eventOverrides: newEventOverrides
489
+ };
490
+ }
491
+
492
+ open.closeName = closeName;
493
+ return {
494
+ [`{${name}}`]: open,
495
+ [closeName]: function ({
496
+ currentElement,
497
+ eventOverrides
498
+ }) {
499
+ const newEventOverrides = {
500
+ [modifierProperty]: false
501
+ };
502
+
503
+ _dom.fireEvent.keyUp(currentElement(), {
504
+ key,
505
+ keyCode,
506
+ which: keyCode,
507
+ ...eventOverrides,
508
+ ...newEventOverrides
509
+ });
510
+
511
+ return {
512
+ eventOverrides: newEventOverrides
513
+ };
514
+ }
515
+ };
516
+ }
517
+
518
+ function handleEnter({
519
+ currentElement,
520
+ eventOverrides
521
+ }) {
522
+ const key = 'Enter';
523
+ const keyCode = 13;
524
+
525
+ const keyDownDefaultNotPrevented = _dom.fireEvent.keyDown(currentElement(), {
526
+ key,
527
+ keyCode,
528
+ which: keyCode,
529
+ ...eventOverrides
530
+ });
531
+
532
+ if (keyDownDefaultNotPrevented) {
533
+ const keyPressDefaultNotPrevented = _dom.fireEvent.keyPress(currentElement(), {
534
+ key,
535
+ keyCode,
536
+ charCode: keyCode,
537
+ ...eventOverrides
538
+ });
539
+
540
+ if (keyPressDefaultNotPrevented) {
541
+ if ((0, _utils.isClickable)(currentElement())) {
542
+ _dom.fireEvent.click(currentElement(), { ...eventOverrides
543
+ });
544
+ }
545
+
546
+ if (currentElement().tagName === 'TEXTAREA') {
547
+ const {
548
+ newValue,
549
+ newSelectionStart
550
+ } = (0, _utils.calculateNewValue)('\n', currentElement());
551
+
552
+ _dom.fireEvent.input(currentElement(), {
553
+ target: {
554
+ value: newValue
555
+ },
556
+ inputType: 'insertLineBreak',
557
+ ...eventOverrides
558
+ });
559
+
560
+ setSelectionRange({
561
+ currentElement,
562
+ newValue,
563
+ newSelectionStart
564
+ });
565
+ }
566
+
567
+ if (currentElement().tagName === 'INPUT' && currentElement().form && (currentElement().form.querySelectorAll('input').length === 1 || currentElement().form.querySelector('input[type="submit"]') || currentElement().form.querySelector('button[type="submit"]'))) {
568
+ _dom.fireEvent.submit(currentElement().form);
569
+ }
570
+ }
571
+ }
572
+
573
+ _dom.fireEvent.keyUp(currentElement(), {
574
+ key,
575
+ keyCode,
576
+ which: keyCode,
577
+ ...eventOverrides
578
+ });
579
+ }
580
+
581
+ function handleEsc({
582
+ currentElement,
583
+ eventOverrides
584
+ }) {
585
+ const key = 'Escape';
586
+ const keyCode = 27;
587
+
588
+ _dom.fireEvent.keyDown(currentElement(), {
589
+ key,
590
+ keyCode,
591
+ which: keyCode,
592
+ ...eventOverrides
593
+ }); // NOTE: Browsers do not fire a keypress on meta key presses
594
+
595
+
596
+ _dom.fireEvent.keyUp(currentElement(), {
597
+ key,
598
+ keyCode,
599
+ which: keyCode,
600
+ ...eventOverrides
601
+ });
602
+ }
603
+
604
+ function handleDel({
605
+ currentElement,
606
+ eventOverrides
607
+ }) {
608
+ const key = 'Delete';
609
+ const keyCode = 46;
610
+
611
+ const keyPressDefaultNotPrevented = _dom.fireEvent.keyDown(currentElement(), {
612
+ key,
613
+ keyCode,
614
+ which: keyCode,
615
+ ...eventOverrides
616
+ });
617
+
618
+ if (keyPressDefaultNotPrevented) {
619
+ fireInputEventIfNeeded({ ...calculateNewDeleteValue(currentElement()),
620
+ eventOverrides: {
621
+ inputType: 'deleteContentForward',
622
+ ...eventOverrides
623
+ },
624
+ currentElement
625
+ });
626
+ }
627
+
628
+ _dom.fireEvent.keyUp(currentElement(), {
629
+ key,
630
+ keyCode,
631
+ which: keyCode,
632
+ ...eventOverrides
633
+ });
634
+ }
635
+
636
+ function handleBackspace({
637
+ currentElement,
638
+ eventOverrides
639
+ }) {
640
+ const key = 'Backspace';
641
+ const keyCode = 8;
642
+
643
+ const keyPressDefaultNotPrevented = _dom.fireEvent.keyDown(currentElement(), {
644
+ key,
645
+ keyCode,
646
+ which: keyCode,
647
+ ...eventOverrides
648
+ });
649
+
650
+ if (keyPressDefaultNotPrevented) {
651
+ fireInputEventIfNeeded({ ...calculateNewBackspaceValue(currentElement()),
652
+ eventOverrides: {
653
+ inputType: 'deleteContentBackward',
654
+ ...eventOverrides
655
+ },
656
+ currentElement
657
+ });
658
+ }
659
+
660
+ _dom.fireEvent.keyUp(currentElement(), {
661
+ key,
662
+ keyCode,
663
+ which: keyCode,
664
+ ...eventOverrides
665
+ });
666
+ }
667
+
668
+ function handleSelectall({
669
+ currentElement
670
+ }) {
671
+ currentElement().setSelectionRange(0, (0, _utils.getValue)(currentElement()).length);
672
+ }
673
+
674
+ function handleSpace(context) {
675
+ if ((0, _utils.isClickable)(context.currentElement())) {
676
+ handleSpaceOnClickable(context);
677
+ return;
678
+ }
679
+
680
+ typeCharacter(' ', context);
681
+ }
682
+
683
+ function handleSpaceOnClickable({
684
+ currentElement,
685
+ eventOverrides
686
+ }) {
687
+ const key = ' ';
688
+ const keyCode = 32;
689
+
690
+ const keyDownDefaultNotPrevented = _dom.fireEvent.keyDown(currentElement(), {
691
+ key,
692
+ keyCode,
693
+ which: keyCode,
694
+ ...eventOverrides
695
+ });
696
+
697
+ if (keyDownDefaultNotPrevented) {
698
+ _dom.fireEvent.keyPress(currentElement(), {
699
+ key,
700
+ keyCode,
701
+ charCode: keyCode,
702
+ ...eventOverrides
703
+ });
704
+ }
705
+
706
+ const keyUpDefaultNotPrevented = _dom.fireEvent.keyUp(currentElement(), {
707
+ key,
708
+ keyCode,
709
+ which: keyCode,
710
+ ...eventOverrides
711
+ });
712
+
713
+ if (keyDownDefaultNotPrevented && keyUpDefaultNotPrevented) {
714
+ _dom.fireEvent.click(currentElement(), { ...eventOverrides
715
+ });
716
+ }
717
+ }