-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
type.ts
706 lines (589 loc) · 22.1 KB
/
type.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
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
import _ from 'lodash'
import Promise from 'bluebird'
import $dom from '../../../dom'
import $elements from '../../../dom/elements'
import $selection from '../../../dom/selection'
import $utils from '../../../cypress/utils'
import $errUtils from '../../../cypress/error_utils'
import $actionability from '../../actionability'
import $Keyboard from '../../../cy/keyboard'
import type { Log } from '../../../cypress/log'
import debugFn from 'debug'
const debug = debugFn('cypress:driver:command:type')
interface InternalTypeOptions extends Partial<Cypress.TypeOptions> {
_log?: Log
$el: JQuery
ensure?: object
verify: boolean
interval?: number
}
interface InternalClearOptions extends Partial<Cypress.ClearOptions> {
_log?: Log
ensure?: object
}
export default function (Commands, Cypress, cy, state, config) {
const { keyboard } = cy.devices
function type (subject, chars, userOptions: Partial<Cypress.TypeOptions> = {}) {
let updateTable
// allow the el we're typing into to be
// changed by options -- used by cy.clear()
const options: InternalTypeOptions = _.defaults({}, userOptions, {
$el: subject,
log: true,
verify: true,
force: false,
delay: config('keystrokeDelay') || $Keyboard.getConfig().keystrokeDelay,
release: true,
parseSpecialCharSequences: true,
waitForAnimations: config('waitForAnimations'),
animationDistanceThreshold: config('animationDistanceThreshold'),
})
if (options.log) {
// figure out the options which actually change the behavior of clicks
const deltaOptions = $utils.filterOutOptions(options)
const table = {}
const getRow = (id, key, event) => {
if (table[id]) {
return table[id]
}
const modifiers = $Keyboard.modifiersToString(keyboard.getActiveModifiers(state))
const formatEventDetails = (obj) => {
return `{ ${(Object.keys(obj)
.filter((v) => Boolean(obj[v]))
.map((v) => `${v}: ${obj[v]}`))
.join(', ')
} }`
}
const obj = table[id] = {
'Typed': key || null,
'Target Element': event.target,
'Events Fired': '',
'Details': formatEventDetails({ code: event.code, which: event.which }),
'Prevented Default': null,
'Active Modifiers': modifiers || null,
}
return obj
}
updateTable = function (id, key, event, value) {
const row = getRow(id, key, event)
row['Events Fired'] += row['Events Fired'] ? `, ${event.type}` : event.type
if (!value) {
row['Prevented Default'] = true
}
}
// transform table object into object with zero based index as keys
const getTableData = () => {
return _.reduce(_.values(table), (memo, value, index) => {
memo[index + 1] = value
return memo
}
, {})
}
options._log = Cypress.log({
message: [chars, deltaOptions],
$el: options.$el,
timeout: options.timeout,
consoleProps () {
return {
'Typed': chars,
'Applied To': $dom.getElements(options.$el),
'Options': deltaOptions,
'table': {
// mouse events tables will take up slot 1 if they're present
// this preserves the order of the tables
2: () => {
return {
name: 'Keyboard Events',
data: getTableData(),
}
},
},
}
},
})
options._log!.snapshot('before', { next: 'after' })
}
if (options.$el.length > 1) {
$errUtils.throwErrByPath('type.multiple_elements', {
onFail: options._log,
args: { num: options.$el.length },
})
}
if (!(_.isString(chars) || _.isFinite(chars))) {
$errUtils.throwErrByPath('type.wrong_type', {
onFail: options._log,
args: { chars },
})
}
if (_.isString(chars) && _.isEmpty(chars)) {
$errUtils.throwErrByPath('type.empty_string', {
onFail: options._log,
args: { chars },
})
}
const isInvalidDelay = (delay) => {
return delay !== undefined && (!_.isNumber(delay) || delay < 0)
}
if (isInvalidDelay(userOptions.delay)) {
$errUtils.throwErrByPath('keyboard.invalid_delay', {
onFail: options._log,
args: {
cmd: 'type',
docsPath: 'type',
option: 'delay',
delay: userOptions.delay,
},
})
}
// specific error if test config keystrokeDelay is invalid
if (isInvalidDelay(config('keystrokeDelay'))) {
$errUtils.throwErrByPath('keyboard.invalid_per_test_delay', {
onFail: options._log,
args: { delay: config('keystrokeDelay') },
})
}
chars = `${chars}`
const win = state('window')
const getDefaultButtons = (form) => {
const formId = CSS.escape(form.attr('id'))
const nestedButtons = form.find('input, button')
const possibleDefaultButtons: JQuery<any> = formId ? $dom.wrap(_.uniq([
...nestedButtons,
...$dom.query('body', form.prop('ownerDocument')).find(`input[form="${formId}"], button[form="${formId}"]`),
])) : nestedButtons
return possibleDefaultButtons.filter((__, el) => {
const $el = $dom.wrap(el)
return (
($dom.isSelector($el, 'input') && $dom.isInputType($el, 'submit')) ||
($dom.isSelector($el, 'button') && !$dom.isInputType($el, 'button') && !$dom.isInputType($el, 'reset'))
)
})
}
const type = function () {
const isFirefoxBefore98 = Cypress.isBrowser('firefox') && Cypress.browserMajorVersion() < 98
const simulateSubmitHandler = function () {
const form = options.$el.parents('form')
if (!form.length) {
return
}
const multipleInputsAllowImplicitSubmissionAndNoSubmitElements = function (form) {
const submits = getDefaultButtons(form)
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission
// some types of inputs can submit the form when hitting {enter}
// but only if they are the sole input that allows implicit submission
// and there are no buttons or input[submits] in the form
const implicitSubmissionInputs = form.find('input').filter((__, input) => {
const $input = $dom.wrap(input)
return $elements.isInputAllowingImplicitFormSubmission($input)
})
return (implicitSubmissionInputs.length > 1) && (submits.length === 0)
}
// throw an error here if there are multiple form parents
// bail if we have multiple inputs allowing implicit submission and no submit elements
if (multipleInputsAllowImplicitSubmissionAndNoSubmitElements(form)) {
return
}
const clickedDefaultButton = function (button) {
// find the 'default button' as per HTML spec and click it natively
// do not issue mousedown / mouseup since this is supposed to be synthentic
if (button.length) {
button.get(0).click()
return true
}
return false
}
const getDefaultButton = (form) => {
return getDefaultButtons(form).first()
}
const defaultButtonisDisabled = (button) => {
return button.prop('disabled')
}
const defaultButton = getDefaultButton(form)
// bail if the default button is in a 'disabled' state
if (defaultButtonisDisabled(defaultButton)) {
return
}
// Before Firefox 98, submit event is automatically fired
// when we send {Enter} KeyboardEvent to the input fields.
// Because of that, we don't have to click the submit buttons.
// Otherwise, we trigger submit events twice.
if (!isFirefoxBefore98) {
// issue the click event to the 'default button' of the form
// we need this to be synchronous so not going through our
// own click command
// as of now, at least in Chrome, causing the click event
// on the button will indeed trigger the form submit event
// so we dont need to fire it manually anymore!
if (!clickedDefaultButton(defaultButton)) {
// if we werent able to click the default button
// then synchronously fire the submit event
// currently this is sync but if we use a waterfall
// promise in the submit command it will break again
// consider changing type to a Promise and juggle logging
return cy.now('submit', form, { log: false, $el: form })
}
}
}
const dispatchChangeEvent = function (el, id) {
const change = document.createEvent('HTMLEvents')
change.initEvent('change', true, false)
const dispatched = el.dispatchEvent(change)
if (id && updateTable) {
return updateTable(id, null, 'change', null, dispatched)
}
}
const needSingleValueChange = (el) => {
return $elements.isNeedSingleValueChangeInputElement(el)
}
// see comment in updateValue below
let typed = ''
const isContentEditable = $elements.isContentEditable(options.$el.get(0))
const isTextarea = $elements.isTextarea(options.$el.get(0))
const fireClickEvent = (el) => {
const ctor = $dom.getDocumentFromElement(el).defaultView!.PointerEvent
const event = new ctor('click')
el.dispatchEvent(event)
}
let keydownEvents: any[] = []
return keyboard.type({
$el: options.$el,
chars,
delay: options.delay,
release: options.release,
parseSpecialCharSequences: options.parseSpecialCharSequences,
window: win,
force: options.force,
onFail: options._log,
updateValue (el, key, charsToType) {
// in these cases, the value must only be set after all
// the characters are input because attemping to set
// a partial/invalid value results in the value being
// set to an empty string
if (needSingleValueChange(el)) {
typed += key
if (typed === charsToType) {
return $elements.setNativeProp(el, 'value', charsToType)
}
}
return $selection.replaceSelectionContents(el, key)
},
onAfterType () {
if (options.release === true) {
state('keyboardModifiers', null)
}
},
onBeforeType (totalKeys) {
// for the total number of keys we're about to
// type, ensure we raise the timeout to account
// for the delay being added to each keystroke
if (options.delay) {
return cy.timeout(totalKeys * options.delay, true, 'type')
}
},
onEvent (id, key, event, value) {
if (updateTable) {
updateTable(id, key, event, value)
}
if (event.type === 'keydown') {
keydownEvents.push(event.target)
}
if (
(
// Before Firefox 98,
// Firefox sends a click event when the Space key is pressed.
// We don't want to send it twice.
!Cypress.isBrowser('firefox') ||
// After Firefox 98,
// it sends a click event automatically if the element is a <button>
// it does not if the element is an <input>
(!isFirefoxBefore98 && $elements.isInput(event.target))
) &&
// Click event is sent after keyup event with space key.
event.type === 'keyup' && event.code === 'Space' &&
// When event is prevented, the click event should not be emitted
!event.defaultPrevented &&
// Click events should be only sent to button-like elements.
// event.target is null when used with shadow DOM.
(event.target && $elements.isButtonLike(event.target)) &&
// When a space key is pressed for input radio elements, the click event is only fired when it's not checked.
!(event.target.tagName === 'INPUT' && event.target.type === 'radio' && event.target.checked === true) &&
// When a space key is pressed on another element, the click event should not be fired.
keydownEvents.includes(event.target)
) {
fireClickEvent(event.target)
keydownEvents = []
// After Firefox 98,
// Firefox doesn't update checkbox automatically even if the click event is sent.
if (Cypress.isBrowser('firefox')) {
if (event.target.type === 'checkbox') {
event.target.checked = !event.target.checked
} else if (event.target.type === 'radio') { // when checked is false, here cannot be reached because of the above condition
event.target.checked = true
}
}
}
},
// fires only when the 'value'
// of input/text/contenteditable
// changes
onValueChange (originalText, el) {
debug('onValueChange', originalText, el)
// contenteditable should never be called here.
// only inputs and textareas can have change events
let changeEvent = state('changeEvent')
if (changeEvent) {
if (!changeEvent(null, true)) {
state('changeEvent', null)
}
return
}
return state('changeEvent', (id, readOnly) => {
const changed =
$elements.getNativeProp(el, 'value') !== originalText
if (!readOnly) {
if (changed) {
dispatchChangeEvent(el, id)
}
state('changeEvent', null)
}
return changed
})
},
onEnterPressed (el) {
// dont dispatch change events or handle
// submit event if we've pressed enter into
// a textarea or contenteditable
if (isTextarea || isContentEditable) {
return
}
// click event is only fired on button, image, submit, reset elements.
// That's why we cannot use $elements.isButtonLike() here.
const type = (type) => $elements.isInputType(el, type)
const sendClickEvent = type('button') || type('image') || type('submit') || type('reset')
// https://github.com/cypress-io/cypress/issues/19541
// Send click event on type('{enter}')
if (sendClickEvent) {
if (
// Before Firefox 98, it sends a click event automatically.
!Cypress.isBrowser('firefox') ||
// After Firefox 98,
// it sends a click event automatically if the element is a <button>
// it does not if the element is an <input>
(!isFirefoxBefore98 && $elements.isInput(el))) {
fireClickEvent(el)
}
}
// if our value has changed since our
// element was activated we need to
// fire a change event immediately
const changeEvent = state('changeEvent')
if (changeEvent) {
changeEvent()
}
// handle submit event handler here
return simulateSubmitHandler()
},
onNoMatchingSpecialChars (chars, allChars) {
if (chars === 'tab') {
$errUtils.throwErrByPath('type.tab', { onFail: options._log })
}
$errUtils.throwErrByPath('type.invalid', {
onFail: options._log,
args: { chars: `{${chars}}`, allChars },
})
},
})
}
const handleFocused = function () {
// if it's the body, don't need to worry about focus
// (unless it can be modified i.e we're in designMode or contenteditable)
const isBody = options.$el.is('body') && !$elements.isContentEditable(options.$el[0])
if (isBody) {
debug('typing into body')
return type()
}
options.ensure = {
position: true,
visibility: true,
notDisabled: true,
notAnimating: true,
notCovered: true,
notReadonly: true,
}
// if the subject is already the focused element, start typing
// we handle contenteditable children by getting the host contenteditable,
// and seeing if that is focused
// Checking first if element is focusable accounts for focusable els inside
// of contenteditables
if ($elements.isFocusedOrInFocused(options.$el.get(0))) {
debug('element is already focused, only checking readOnly property')
options.ensure = {
notReadonly: true,
}
}
return $actionability.verify(cy, options.$el, config, options, {
onScroll ($el, type) {
return Cypress.action('cy:scrolled', $el, type)
},
onReady ($elToClick) {
// if we dont have a focused element
// or if we do and its not ourselves
// then issue the click
if ($elements.isFocusedOrInFocused($elToClick[0])) {
return type()
}
// click the element first to simulate focus
// and typical user behavior in case the window
// is out of focus
// cannot just call .focus, since children of contenteditable will not receive cursor
// with .focus()
return cy.now('click', $elToClick, {
$el: $elToClick,
log: false,
verify: false,
_log: options._log,
force: true, // force the click, avoid waiting
timeout: options.timeout,
interval: options.interval,
errorOnSelect: false,
scrollBehavior: options.scrollBehavior,
})
.then(() => {
let activeElement = $elements.getActiveElByDocument($elToClick)
if (!options.force && activeElement === null) {
const node = $dom.stringify($elToClick)
const onFail = options._log
if ($dom.isTextLike($elToClick[0])) {
$errUtils.throwErrByPath('type.not_actionable_textlike', {
onFail,
args: { node },
})
}
$errUtils.throwErrByPath('type.not_on_typeable_element', {
onFail,
args: { node },
})
}
return type()
})
},
})
}
return handleFocused()
.then(() => {
cy.timeout($actionability.delay, true, 'type')
return Promise
.delay($actionability.delay, 'type')
.then(() => {
// command which consume cy.type may
// want to handle verification themselves
if (options.verify === false) {
return options.$el
}
const verifyAssertions = () => {
return cy.verifyUpcomingAssertions(options.$el, options, {
onRetry: verifyAssertions,
})
}
return verifyAssertions()
})
})
}
function clear (subject, userOptions: Partial<Cypress.ClearOptions> = {}) {
const options: InternalClearOptions = _.defaults({}, userOptions, {
log: true,
force: false,
waitForAnimations: config('waitForAnimations'),
animationDistanceThreshold: config('animationDistanceThreshold'),
})
// blow up if any member of the subject
// isnt a textarea or text-like
const clear = function (el) {
const $el = $dom.wrap(el)
if (options.log) {
// figure out the options which actually change the behavior of clicks
const deltaOptions = $utils.filterOutOptions(options)
options._log = Cypress.log({
message: deltaOptions,
$el,
timeout: options.timeout,
consoleProps () {
return {
'Applied To': $dom.getElements($el),
'Elements': $el.length,
'Options': deltaOptions,
}
},
})
}
const callTypeCmd = ($el) => {
return cy.now('type', $el, '{selectall}{del}', {
$el,
log: false,
verify: false, // handle verification ourselves
_log: options._log,
force: options.force,
timeout: options.timeout,
interval: options.interval,
waitForAnimations: options.waitForAnimations,
animationDistanceThreshold: options.animationDistanceThreshold,
scrollBehavior: options.scrollBehavior,
}).then(() => {
if (options._log) {
options._log.snapshot().end()
}
return null
})
}
const throwError = ($el) => {
const node = $dom.stringify($el)
const word = $utils.plural(subject, 'contains', 'is')
$errUtils.throwErrByPath('clear.invalid_element', {
onFail: options._log,
args: { word, node },
})
}
if (!$dom.isTextLike($el.get(0))) {
options.ensure = {
position: true,
visibility: true,
notDisabled: true,
notAnimating: true,
notCovered: true,
notReadonly: true,
}
return $actionability.verify(cy, $el, config, options, {
onScroll ($el, type) {
return Cypress.action('cy:scrolled', $el, type)
},
onReady ($elToClick) {
let activeElement = $elements.getActiveElByDocument($elToClick)
if (!options.force && activeElement === null || !$dom.isTextLike($elToClick.get(0))) {
throwError($el)
}
return callTypeCmd($elToClick)
},
})
}
return callTypeCmd($el)
}
return Promise
.resolve(subject.toArray())
.each(clear)
.then(() => {
const verifyAssertions = () => {
return cy.verifyUpcomingAssertions(subject, options, {
onRetry: verifyAssertions,
})
}
return verifyAssertions()
})
}
return Commands.addAll(
{ prevSubject: 'element' },
{
type,
clear,
},
)
}