-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathtype.js
736 lines (654 loc) Β· 19.4 KB
/
type.js
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
// TODO: wrap in asyncWrapper
import {
fireEvent,
getConfig as getDOMTestingLibraryConfig,
} from '@testing-library/dom'
import {
getActiveElement,
calculateNewValue,
setSelectionRangeIfNecessary,
isClickable,
isValidDateValue,
getSelectionRange,
getValue,
isContentEditable,
isValidInputTimeValue,
buildTimeValue,
} from './utils'
import {click} from './click'
import {navigationKey} from './keys/navigation-key'
const modifierCallbackMap = {
...createModifierCallbackEntries({
name: 'shift',
key: 'Shift',
keyCode: 16,
modifierProperty: 'shiftKey',
}),
...createModifierCallbackEntries({
name: 'ctrl',
key: 'Control',
keyCode: 17,
modifierProperty: 'ctrlKey',
}),
...createModifierCallbackEntries({
name: 'alt',
key: 'Alt',
keyCode: 18,
modifierProperty: 'altKey',
}),
...createModifierCallbackEntries({
name: 'meta',
key: 'Meta',
keyCode: 93,
modifierProperty: 'metaKey',
}),
// capslock is inline because of the need to fire both keydown and keyup on use, while preserving the modifier state.
'{capslock}': function capslockOn({currentElement, eventOverrides}) {
const newEventOverrides = {modifierCapsLock: true}
fireEvent.keyDown(currentElement(), {
key: 'CapsLock',
keyCode: 20,
which: 20,
...eventOverrides,
...newEventOverrides,
})
fireEvent.keyUp(currentElement(), {
key: 'CapsLock',
keyCode: 20,
which: 20,
...eventOverrides,
...newEventOverrides,
})
return {eventOverrides: newEventOverrides}
},
'{/capslock}': function capslockOff({currentElement, eventOverrides}) {
const newEventOverrides = {modifierCapsLock: false}
fireEvent.keyDown(currentElement(), {
key: 'CapsLock',
keyCode: 20,
which: 20,
...eventOverrides,
...newEventOverrides,
})
fireEvent.keyUp(currentElement(), {
key: 'CapsLock',
keyCode: 20,
which: 20,
...eventOverrides,
...newEventOverrides,
})
return {eventOverrides: newEventOverrides}
},
}
const specialCharCallbackMap = {
'{arrowleft}': navigationKey('ArrowLeft'),
'{arrowright}': navigationKey('ArrowRight'),
'{enter}': handleEnter,
'{esc}': handleEsc,
'{del}': handleDel,
'{backspace}': handleBackspace,
'{selectall}': handleSelectall,
'{space}': handleSpace,
' ': handleSpace,
}
function wait(time) {
return new Promise(resolve => setTimeout(() => resolve(), time))
}
// this needs to be wrapped in the event/asyncWrapper for React's act and angular's change detection
// depending on whether it will be async.
async function type(element, text, {delay = 0, ...options} = {}) {
// we do not want to wrap in the asyncWrapper if we're not
// going to actually be doing anything async, so we only wrap
// if the delay is greater than 0
let result
if (delay > 0) {
await getDOMTestingLibraryConfig().asyncWrapper(async () => {
result = await typeImpl(element, text, {delay, ...options})
})
} else {
result = typeImpl(element, text, {delay, ...options})
}
return result
}
async function typeImpl(
element,
text,
{
delay,
skipClick = false,
skipAutoClose = false,
initialSelectionStart,
initialSelectionEnd,
},
) {
if (element.disabled) return
if (!skipClick) click(element)
if (isContentEditable(element) && document.getSelection().rangeCount === 0) {
const range = document.createRange()
range.setStart(element, 0)
range.setEnd(element, 0)
document.getSelection().addRange(range)
}
// The focused element could change between each event, so get the currently active element each time
const currentElement = () => getActiveElement(element.ownerDocument)
// by default, a new element has it's selection start and end at 0
// but most of the time when people call "type", they expect it to type
// at the end of the current input value. So, if the selection start
// and end are both the default of 0, then we'll go ahead and change
// them to the length of the current value.
// the only time it would make sense to pass the initialSelectionStart or
// initialSelectionEnd is if you have an input with a value and want to
// explicitely start typing with the cursor at 0. Not super common.
const value = getValue(currentElement())
const {selectionStart, selectionEnd} = getSelectionRange(element)
if (value != null && selectionStart === 0 && selectionEnd === 0) {
setSelectionRangeIfNecessary(
currentElement(),
initialSelectionStart ?? value.length,
initialSelectionEnd ?? value.length,
)
}
const eventCallbacks = queueCallbacks()
await runCallbacks(eventCallbacks)
function queueCallbacks() {
const callbacks = []
let remainingString = text
while (remainingString) {
const {callback, remainingString: newRemainingString} = getNextCallback(
remainingString,
skipAutoClose,
)
callbacks.push(callback)
remainingString = newRemainingString
}
return callbacks
}
async function runCallbacks(callbacks) {
const eventOverrides = {}
let prevWasMinus, prevWasPeriod, prevValue, typedValue
for (const callback of callbacks) {
if (delay > 0) await wait(delay)
if (!currentElement().disabled) {
const returnValue = callback({
currentElement,
prevWasMinus,
prevWasPeriod,
prevValue,
eventOverrides,
typedValue,
})
Object.assign(eventOverrides, returnValue?.eventOverrides)
prevWasMinus = returnValue?.prevWasMinus
prevWasPeriod = returnValue?.prevWasPeriod
prevValue = returnValue?.prevValue
typedValue = returnValue?.typedValue
}
}
}
}
function getNextCallback(remainingString, skipAutoClose) {
const modifierCallback = getModifierCallback(remainingString, skipAutoClose)
if (modifierCallback) {
return modifierCallback
}
const specialCharCallback = getSpecialCharCallback(remainingString)
if (specialCharCallback) {
return specialCharCallback
}
return getTypeCallback(remainingString)
}
function getModifierCallback(remainingString, skipAutoClose) {
const modifierKey = Object.keys(modifierCallbackMap).find(key =>
remainingString.startsWith(key),
)
if (!modifierKey) {
return null
}
const callback = modifierCallbackMap[modifierKey]
// if this modifier has an associated "close" callback and the developer
// doesn't close it themselves, then we close it for them automatically
// Effectively if they send in: '{alt}a' then we type: '{alt}a{/alt}'
if (
!skipAutoClose &&
callback.closeName &&
!remainingString.includes(callback.closeName)
) {
remainingString += callback.closeName
}
remainingString = remainingString.slice(modifierKey.length)
return {
callback,
remainingString,
}
}
function getSpecialCharCallback(remainingString) {
const specialChar = Object.keys(specialCharCallbackMap).find(key =>
remainingString.startsWith(key),
)
if (!specialChar) {
return null
}
return {
callback: specialCharCallbackMap[specialChar],
remainingString: remainingString.slice(specialChar.length),
}
}
function getTypeCallback(remainingString) {
const character = remainingString[0]
const callback = context => typeCharacter(character, context)
return {
callback,
remainingString: remainingString.slice(1),
}
}
function setSelectionRange({currentElement, newValue, newSelectionStart}) {
// if we *can* change the selection start, then we will if the new value
// is the same as the current value (so it wasn't programatically changed
// when the fireEvent.input was triggered).
// The reason we have to do this at all is because it actually *is*
// programmatically changed by fireEvent.input, so we have to simulate the
// browser's default behavior
const value = getValue(currentElement())
if (value === newValue) {
setSelectionRangeIfNecessary(
currentElement(),
newSelectionStart,
newSelectionStart,
)
} else {
// If the currentValue is different than the expected newValue and we *can*
// change the selection range, than we should set it to the length of the
// currentValue to ensure that the browser behavior is mimicked.
setSelectionRangeIfNecessary(currentElement(), value.length, value.length)
}
}
function fireInputEventIfNeeded({
currentElement,
newValue,
newSelectionStart,
eventOverrides,
}) {
const prevValue = getValue(currentElement())
if (
!currentElement().readOnly &&
!isClickable(currentElement()) &&
newValue !== prevValue
) {
if (isContentEditable(currentElement())) {
fireEvent.input(currentElement(), {
target: {textContent: newValue},
...eventOverrides,
})
} else {
fireEvent.input(currentElement(), {
target: {value: newValue},
...eventOverrides,
})
}
setSelectionRange({
currentElement,
newValue,
newSelectionStart,
})
}
return {prevValue}
}
function typeCharacter(
char,
{
currentElement,
prevWasMinus = false,
prevWasPeriod = false,
prevValue = '',
typedValue = '',
eventOverrides,
},
) {
const key = char // TODO: check if this also valid for characters with diacritic markers e.g. ΓΊΓ© etc
const keyCode = char.charCodeAt(0)
let nextPrevWasMinus, nextPrevWasPeriod
const textToBeTyped = typedValue + char
const keyDownDefaultNotPrevented = fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyDownDefaultNotPrevented) {
const keyPressDefaultNotPrevented = fireEvent.keyPress(currentElement(), {
key,
keyCode,
charCode: keyCode,
...eventOverrides,
})
if (getValue(currentElement()) != null && keyPressDefaultNotPrevented) {
let newEntry = char
if (prevWasMinus) {
newEntry = `-${char}`
} else if (prevWasPeriod) {
newEntry = `${prevValue}.${char}`
}
if (isValidDateValue(currentElement(), textToBeTyped)) {
newEntry = textToBeTyped
}
const timeNewEntry = buildTimeValue(textToBeTyped)
if (isValidInputTimeValue(currentElement(), timeNewEntry)) {
newEntry = timeNewEntry
}
const inputEvent = fireInputEventIfNeeded({
...calculateNewValue(newEntry, currentElement()),
eventOverrides: {
data: key,
inputType: 'insertText',
...eventOverrides,
},
currentElement,
})
prevValue = inputEvent.prevValue
if (isValidDateValue(currentElement(), textToBeTyped)) {
fireEvent.change(currentElement(), {target: {value: textToBeTyped}})
}
fireChangeForInputTimeIfValid(currentElement, prevValue, timeNewEntry)
// typing "-" into a number input will not actually update the value
// so for the next character we type, the value should be set to
// `-${newEntry}`
// we also preserve the prevWasMinus when the value is unchanged due
// to typing an invalid character (typing "-a3" results in "-3")
// same applies for the decimal character.
if (currentElement().type === 'number') {
const newValue = getValue(currentElement())
if (newValue === prevValue && newEntry !== '-') {
nextPrevWasMinus = prevWasMinus
} else {
nextPrevWasMinus = newEntry === '-'
}
if (newValue === prevValue && newEntry !== '.') {
nextPrevWasPeriod = prevWasPeriod
} else {
nextPrevWasPeriod = newEntry === '.'
}
}
}
}
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
return {
prevWasMinus: nextPrevWasMinus,
prevWasPeriod: nextPrevWasPeriod,
prevValue,
typedValue: textToBeTyped,
}
}
function fireChangeForInputTimeIfValid(
currentElement,
prevValue,
timeNewEntry,
) {
if (
isValidInputTimeValue(currentElement(), timeNewEntry) &&
prevValue !== timeNewEntry
) {
fireEvent.change(currentElement(), {target: {value: timeNewEntry}})
}
}
// yes, calculateNewBackspaceValue and calculateNewValue look extremely similar
// and you may be tempted to create a shared abstraction.
// If you, brave soul, decide to so endevor, please increment this count
// when you inevitably fail: 1
function calculateNewBackspaceValue(element) {
const {selectionStart, selectionEnd} = getSelectionRange(element)
const value = getValue(element)
let newValue, newSelectionStart
if (selectionStart === null) {
// at the end of an input type that does not support selection ranges
// https://github.com/testing-library/user-event/issues/316#issuecomment-639744793
newValue = value.slice(0, value.length - 1)
newSelectionStart = selectionStart - 1
} else if (selectionStart === selectionEnd) {
if (selectionStart === 0) {
// at the beginning of the input
newValue = value
newSelectionStart = selectionStart
} else if (selectionStart === value.length) {
// at the end of the input
newValue = value.slice(0, value.length - 1)
newSelectionStart = selectionStart - 1
} else {
// in the middle of the input
newValue = value.slice(0, selectionStart - 1) + value.slice(selectionEnd)
newSelectionStart = selectionStart - 1
}
} else {
// we have something selected
const firstPart = value.slice(0, selectionStart)
newValue = firstPart + value.slice(selectionEnd)
newSelectionStart = firstPart.length
}
return {newValue, newSelectionStart}
}
function calculateNewDeleteValue(element) {
const {selectionStart, selectionEnd} = getSelectionRange(element)
const value = getValue(element)
let newValue
if (selectionStart === null) {
// at the end of an input type that does not support selection ranges
// https://github.com/testing-library/user-event/issues/316#issuecomment-639744793
newValue = value
} else if (selectionStart === selectionEnd) {
if (selectionStart === 0) {
// at the beginning of the input
newValue = value.slice(1)
} else if (selectionStart === value.length) {
// at the end of the input
newValue = value
} else {
// in the middle of the input
newValue = value.slice(0, selectionStart) + value.slice(selectionEnd + 1)
}
} else {
// we have something selected
const firstPart = value.slice(0, selectionStart)
newValue = firstPart + value.slice(selectionEnd)
}
return {newValue, newSelectionStart: selectionStart}
}
function createModifierCallbackEntries({name, key, keyCode, modifierProperty}) {
const openName = `{${name}}`
const closeName = `{/${name}}`
function open({currentElement, eventOverrides}) {
const newEventOverrides = {[modifierProperty]: true}
fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
...newEventOverrides,
})
return {eventOverrides: newEventOverrides}
}
open.closeName = closeName
function close({currentElement, eventOverrides}) {
const newEventOverrides = {[modifierProperty]: false}
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
...newEventOverrides,
})
return {eventOverrides: newEventOverrides}
}
return {
[openName]: open,
[closeName]: close,
}
}
function handleEnter({currentElement, eventOverrides}) {
const key = 'Enter'
const keyCode = 13
const keyDownDefaultNotPrevented = fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyDownDefaultNotPrevented) {
const keyPressDefaultNotPrevented = fireEvent.keyPress(currentElement(), {
key,
keyCode,
charCode: keyCode,
...eventOverrides,
})
if (keyPressDefaultNotPrevented) {
if (isClickable(currentElement())) {
fireEvent.click(currentElement(), {
...eventOverrides,
})
}
if (currentElement().tagName === 'TEXTAREA') {
const {newValue, newSelectionStart} = calculateNewValue(
'\n',
currentElement(),
)
fireEvent.input(currentElement(), {
target: {value: newValue},
inputType: 'insertLineBreak',
...eventOverrides,
})
setSelectionRange({
currentElement,
newValue,
newSelectionStart,
})
}
if (
currentElement().tagName === 'INPUT' &&
currentElement().form &&
(currentElement().form.querySelectorAll('input').length === 1 ||
currentElement().form.querySelector('input[type="submit"]') ||
currentElement().form.querySelector('button[type="submit"]'))
) {
fireEvent.submit(currentElement().form)
}
}
}
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
}
function handleEsc({currentElement, eventOverrides}) {
const key = 'Escape'
const keyCode = 27
fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
// NOTE: Browsers do not fire a keypress on meta key presses
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
}
function handleDel({currentElement, eventOverrides}) {
const key = 'Delete'
const keyCode = 46
const keyPressDefaultNotPrevented = fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyPressDefaultNotPrevented) {
fireInputEventIfNeeded({
...calculateNewDeleteValue(currentElement()),
eventOverrides: {
inputType: 'deleteContentForward',
...eventOverrides,
},
currentElement,
})
}
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
}
function handleBackspace({currentElement, eventOverrides}) {
const key = 'Backspace'
const keyCode = 8
const keyPressDefaultNotPrevented = fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyPressDefaultNotPrevented) {
fireInputEventIfNeeded({
...calculateNewBackspaceValue(currentElement()),
eventOverrides: {
inputType: 'deleteContentBackward',
...eventOverrides,
},
currentElement,
})
}
fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
}
function handleSelectall({currentElement}) {
currentElement().setSelectionRange(0, getValue(currentElement()).length)
}
function handleSpace(context) {
if (isClickable(context.currentElement())) {
handleSpaceOnClickable(context)
return
}
typeCharacter(' ', context)
}
function handleSpaceOnClickable({currentElement, eventOverrides}) {
const key = ' '
const keyCode = 32
const keyDownDefaultNotPrevented = fireEvent.keyDown(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyDownDefaultNotPrevented) {
fireEvent.keyPress(currentElement(), {
key,
keyCode,
charCode: keyCode,
...eventOverrides,
})
}
const keyUpDefaultNotPrevented = fireEvent.keyUp(currentElement(), {
key,
keyCode,
which: keyCode,
...eventOverrides,
})
if (keyDownDefaultNotPrevented && keyUpDefaultNotPrevented) {
fireEvent.click(currentElement(), {
...eventOverrides,
})
}
}
export {type}