-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathcommand.tsx
553 lines (480 loc) · 18 KB
/
command.tsx
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
import _ from 'lodash'
import cs from 'classnames'
import Markdown from 'markdown-it'
import { action, observable, makeObservable } from 'mobx'
import { observer } from 'mobx-react'
import React, { Component } from 'react'
import Tooltip from '@cypress/react-tooltip'
import appState, { AppState } from '../lib/app-state'
import events, { Events } from '../lib/events'
import FlashOnClick from '../lib/flash-on-click'
import StateIcon from '../lib/state-icon'
import Tag from '../lib/tag'
import type { TimeoutID } from '../lib/types'
import runnablesStore, { RunnablesStore } from '../runnables/runnables-store'
import type { Alias, AliasObject } from '../instruments/instrument-model'
import { determineTagType } from '../sessions/utils'
import type CommandModel from './command-model'
import type { RenderProps } from './command-model'
import TestError from '../errors/test-error'
import ChevronIcon from '@packages/frontend-shared/src/assets/icons/chevron-down-small_x8.svg'
import HiddenIcon from '@packages/frontend-shared/src/assets/icons/general-eye-closed_x16.svg'
import PinIcon from '@packages/frontend-shared/src/assets/icons/object-pin_x16.svg'
import RunningIcon from '@packages/frontend-shared/src/assets/icons/status-running_x16.svg'
const displayName = (model: CommandModel) => model.displayName || model.name
const nameClassName = (name: string) => name.replace(/(\s+)/g, '-')
const md = new Markdown()
const mdOnlyHTML = new Markdown('zero').enable(['html_inline', 'html_block'])
const asterisksRegex = /^\*\*(.+?)\*\*$/gs
// regex to match everything outside of expected/actual values like:
// 'expected **<span>** to exist in the DOM'
// `expected **glob*glob** to contain *****`
// `expected **<span>** to have CSS property **background-color** with the value **rgb(0, 0, 0)**, but the value was **rgba(0, 0, 0, 0)**`
// `expected **foo** to have length above **1** but got **0**`
// `Custom message expected **<span>** to exist in the DOM`
const assertionRegex = /^.*?expected | to[^\*]+| not[^\*]+| with[^\*]+|,? but[^\*]+/g
// used to format the display of command messages and error messages
// we use markdown syntax within our error messages (code ticks, urls, etc)
// and cy.log and Cypress.log supports markdown formatting
export const formattedMessage = (message: string, name?: string) => {
if (!message) return ''
// if the command has url args, don't format those chars like __ and ~~
if (name === 'visit' || name === 'request' || name === 'origin') {
return message
}
// the command message is formatted as '(Optional Custom Msg:) expected <actual> to {assertion} <expected>'
const assertionArray = message.match(assertionRegex)
if (name === 'assert' && assertionArray) {
const expectedActualArray = () => {
// get the expected and actual values of assertions
const splitTrim = message.split(assertionRegex).filter(Boolean).map((s) => s.trim())
// replace outside double asterisks with strong tags
return splitTrim.map((s) => {
// we want to escape HTML chars so that they display
// correctly in the command log: <p> -> <p>
const HTMLEscapedString = mdOnlyHTML.renderInline(s)
return HTMLEscapedString.replace(asterisksRegex, `<strong>$1</strong>`)
})
}
// for assertions print the exact text so that characters like _ and *
// are not escaped in the assertion display when comparing values
const result = assertionArray.flatMap((s, index) => [s, expectedActualArray()[index]])
return result.join('')
}
// format markdown for everything else
return md.renderInline(message)
}
const invisibleMessage = (model: CommandModel) => {
return model.numElements > 1 ?
'One or more matched elements are not visible.' :
'This element is not visible.'
}
const numberOfChildrenMessage = (numChildren, event?: boolean) => {
if (event) {
return `This event occurred ${numChildren} times`
}
return `${numChildren} ${numChildren > 1 ? 'logs' : 'log'} currently hidden`
}
const shouldShowCount = (aliasesWithDuplicates: Array<Alias> | null, aliasName: Alias, model: CommandModel) => {
if (model.aliasType !== 'route') {
return false
}
return _.includes(aliasesWithDuplicates, aliasName)
}
/**
* NavColumns Rules:
* > Command Number Column
* - When the command is executing, it is pending and renders the pending icon
* - When the command is finished, it displays the command number
* - Commands will render a command number, where Events and System logs do not
* - When the command is finished and the user has pinned the log, it displays the pin icon
*
* > Expander Column
* - When the log is a group log and it has children logs, it will display the chevron icon
*/
const NavColumns = observer(({ model, isPinned, toggleColumnPin }) => (
<>
<div className='command-number-column' onClick={toggleColumnPin}>
{model._isPending() && <RunningIcon data-cy="reporter-running-icon" className='fa-spin' />}
{(!model._isPending() && isPinned) && <PinIcon className='command-pin' />}
{(!model._isPending() && !isPinned) && model.number}
</div>
{model.hasChildren && (
<div className='command-expander-column' onClick={() => model.toggleOpen()}>
<ChevronIcon className={cs('command-expander', { 'command-expander-is-open': model.hasChildren && !!model.isOpen })} />
</div>
)}
</>
))
interface AliasReferenceProps {
aliasObj: AliasObject
model: CommandModel
aliasesWithDuplicates: Array<Alias> | null
}
const AliasReference = observer(({ aliasObj, model, aliasesWithDuplicates }: AliasReferenceProps) => {
const showCount = shouldShowCount(aliasesWithDuplicates, aliasObj.name, model)
const toolTipMessage = showCount ? `Found ${aliasObj.ordinal} alias for: '${aliasObj.name}'` : `Found an alias for: '${aliasObj.name}'`
return (
<Tag
content={`@${aliasObj.name}`}
type={model.aliasType}
count={showCount ? aliasObj.cardinal : undefined}
tooltipMessage={toolTipMessage}
customClassName='command-alias'
/>
)
})
interface AliasesReferencesProps {
model: CommandModel
aliasesWithDuplicates: Array<Alias> | null
}
const AliasesReferences = observer(({ model, aliasesWithDuplicates }: AliasesReferencesProps) => {
const aliases = ([] as Array<AliasObject>).concat((model.referencesAlias as AliasObject))
if (!aliases.length) {
return null
}
return (
<span className='command-aliases'>
{aliases.map((aliasObj) => (
<AliasReference
key={aliasObj.name + aliasObj.cardinal}
aliasObj={aliasObj}
model={model}
aliasesWithDuplicates={aliasesWithDuplicates}
/>
))}
</span>
)
})
const Interceptions = observer(({ interceptions, wentToOrigin, status }: RenderProps) => {
if (!interceptions?.length) {
return null
}
const interceptsTitle = (
<span>
{wentToOrigin ? '' : <>This request did not go to origin because the response was stubbed.<br/></>}
This request matched:
<ul>
{interceptions?.map(({ command, alias, type }, i) => (
<li key={i}>
<code>cy.{command}()</code> {type} with {alias ? <>alias <code>@{alias}</code></> : 'no alias'}
</li>
))}
</ul>
</span>
)
const count = interceptions.length
const displayAlias = interceptions[count - 1].alias
return (
<Tag
content={<>
{status && <span className='status'>{status} </span>}
{displayAlias || <em className='no-alias'>no alias</em>}
</>}
count={count > 1 ? count : undefined}
type='route'
tooltipMessage={interceptsTitle}
customClassName='command-interceptions'
/>
)
})
interface AliasesProps {
model: CommandModel
}
const Aliases = observer(({ model }: AliasesProps) => {
if (!model.alias || model.aliasType === 'route') return null
const aliases = ([] as Array<Alias>).concat(model.alias)
return (
<span>
{aliases.map((alias) => {
const aliases = [alias]
if (model.hasChildren && !model.isOpen) {
aliases.push(..._.compact(model.children.map((dupe) => dupe.alias)))
}
return (
<Tag
key={alias}
content={aliases.join(', ')}
type={model.aliasType}
tooltipMessage={`${model.displayMessage} aliased as: ${aliases.map((alias) => `'${alias}'`).join(', ')}`}
customClassName='command-alias'
/>
)
})}
</span>
)
})
interface MessageProps {
model: CommandModel
}
const Message = observer(({ model }: MessageProps) => (
<span className='command-message'>
{!!model.renderProps.indicator && (
<i
className={
cs(
model.renderProps.wentToOrigin ? 'fas' : 'far',
'fa-circle',
`command-message-indicator-${model.renderProps.indicator}`,
)
}
/>
)}
{!!model.displayMessage && <span
className='command-message-text'
dangerouslySetInnerHTML={{ __html: formattedMessage(model.displayMessage, model.name) }}
/>}
</span>
))
interface ProgressProps {
model: CommandModel
}
const Progress = observer(({ model }: ProgressProps) => {
if (model.state !== 'pending' || !model.timeout || !model.wallClockStartedAt) {
return null
}
const timeElapsed = Date.now() - new Date(model.wallClockStartedAt).getTime()
const timeRemaining = model.timeout ? model.timeout - timeElapsed : 0
const percentageRemaining = timeRemaining / model.timeout || 0
// we add a key to the span to ensure a rerender and restart of the animation on change
return (
<div className='command-progress'>
<span style={{ animationDuration: `${timeRemaining}ms`, transform: `scaleX(${percentageRemaining})` }} key={timeRemaining} />
</div>
)
})
interface Props {
model: CommandModel
aliasesWithDuplicates: Array<Alias> | null
appState: AppState
events: Events
runnablesStore: RunnablesStore
groupId?: number
}
const CommandDetails = observer(({ model, groupId, aliasesWithDuplicates }) => (
<span className={cs('command-info')}>
<span className='command-method'>
<span>
{model.event && model.type !== 'system' ? `(${displayName(model)})` : displayName(model)}
</span>
</span>
{!!groupId && model.type === 'system' && model.state === 'failed' && <StateIcon aria-hidden className='failed-indicator' state={model.state}/>}
{model.referencesAlias ?
<AliasesReferences model={model} aliasesWithDuplicates={aliasesWithDuplicates} />
: <Message model={model} />
}
</span>
))
const CommandControls = observer(({ model, commandName, events }) => {
const displayNumOfElements = model.state !== 'pending' && model.numElements != null && model.numElements !== 1
const isSystemEvent = model.type === 'system' && model.event
const isSessionCommand = commandName === 'session'
const displayNumOfChildren = !isSystemEvent && !isSessionCommand && model.hasChildren && !model.isOpen
const _removeStudioCommand = (e: React.MouseEvent<HTMLElement, globalThis.MouseEvent>) => {
e.preventDefault()
e.stopPropagation()
events.emit('studio:remove:command', model.number)
}
return (
<span className='command-controls'>
{model.type === 'parent' && model.isStudio && (
<i
className='far fa-times-circle studio-command-remove'
onClick={_removeStudioCommand}
/>
)}
{isSessionCommand && (
<Tag
content={model.sessionInfo?.status}
type={determineTagType(model.state)}
/>
)}
{!model.visible && (
<Tooltip placement='top' title={invisibleMessage(model)} className='cy-tooltip'>
<span>
<HiddenIcon className='command-invisible' />
</span>
</Tooltip>
)}
{displayNumOfElements && (
<Tag
content={model.numElements.toString()}
type='count'
tooltipMessage={`${model.numElements} matched elements`}
customClassName='num-elements'
/>
)}
<span className='alias-container'>
<Interceptions {...model.renderProps} />
<Aliases model={model} />
{displayNumOfChildren && (
<Tag
content={model.numChildren}
type='count'
tooltipMessage={numberOfChildrenMessage(model.numChildren, model.event)}
customClassName='num-children'
/>
)}
</span>
</span>
)
})
@observer
class Command extends Component<Props> {
@observable isOpen: boolean|null = null
private _showTimeout?: TimeoutID
static defaultProps = {
appState,
events,
runnablesStore,
}
constructor (props: Props) {
super(props)
makeObservable(this)
}
render () {
const { model, aliasesWithDuplicates } = this.props
if (model.group && this.props.groupId !== model.group) {
return null
}
const commandName = model.name ? nameClassName(model.name) : ''
const groupPlaceholder: Array<JSX.Element> = []
let groupLevel = 0
if (model.groupLevel !== undefined) {
// cap the group nesting to 5 levels to keep the log text legible
groupLevel = model.groupLevel < 6 ? model.groupLevel : 5
for (let i = 1; i < groupLevel; i++) {
groupPlaceholder.push(<span key={`${this.props.groupId}-${i}`} className='command-group-block' />)
}
}
return (
<>
<li className={cs('command', `command-name-${commandName}`, { 'command-is-studio': model.isStudio })}>
<div
className={cs(
'command-wrapper',
`command-state-${model.state}`,
`command-type-${model.type}`,
{
'command-is-event': !!model.event,
'command-is-pinned': this._isPinned(),
'command-is-interactive': (model.hasConsoleProps || model.hasSnapshot),
},
)}
>
<NavColumns model={model} isPinned={this._isPinned()} toggleColumnPin={this._toggleColumnPin} />
<FlashOnClick
message='Printed output to your console'
onClick={this._toggleColumnPin}
shouldShowMessage={this._shouldShowClickMessage}
wrapperClassName={cs('command-pin-target', { 'command-group': !!this.props.groupId })}
>
<div
className='command-wrapper-text'
onMouseEnter={() => this._snapshot(true)}
onMouseLeave={() => this._snapshot(false)}
>
{groupPlaceholder}
<CommandDetails model={model} groupId={this.props.groupId} aliasesWithDuplicates={aliasesWithDuplicates} />
<CommandControls model={model} commandName={commandName} events={this.props.events} />
</div>
</FlashOnClick>
</div>
<Progress model={model} />
{this._children()}
</li>
{model.showError && (
<li>
<TestError
err={model.err}
testId={model.testId}
commandId={model.id}
// if the err is recovered and the current command is a log group, nest the test error within the group
groupLevel={model.group && model.hasChildren ? ++groupLevel : groupLevel}
/>
</li>
)}
</>
)
}
_children () {
const { appState, events, model, runnablesStore } = this.props
if (!model.hasChildren || !model.isOpen) {
return null
}
return (
<ul className='command-child-container'>
{model.children.map((child) => (
<Command
key={child.id}
model={child}
appState={appState}
events={events}
runnablesStore={runnablesStore}
aliasesWithDuplicates={null}
groupId={model.id}
/>
))}
</ul>
)
}
_isPinned () {
return this.props.appState.pinnedSnapshotId === this.props.model.id
}
_shouldShowClickMessage = () => {
return !this.props.appState.isRunning && !!this.props.model.hasConsoleProps
}
@action _toggleColumnPin = () => {
if (this.props.appState.isRunning) return
const { testId, id } = this.props.model
if (this._isPinned()) {
this.props.appState.pinnedSnapshotId = null
this.props.events.emit('unpin:snapshot', testId, id)
this._snapshot(true)
} else {
this.props.appState.pinnedSnapshotId = id as number
this.props.events.emit('pin:snapshot', testId, id)
this.props.events.emit('show:command', testId, id)
}
}
// snapshot rules
//
// 1. when we hover over a command, wait 50 ms
// if we're still hovering, send show:snapshot
//
// 2. when we hover off a command, wait 50 ms
// and if we are still in a non-showing state
// meaning we have moused over nothing instead
// of a different command, send hide:snapshot
//
// this prevents heavy CPU usage when hovering
// up and down over commands. it also prevents
// restoring to the original through all of that.
// additionally when quickly moving your mouse
// over many commands, unless you're hovered for
// 50ms, it won't show the snapshot at all. so we
// optimize for both snapshot showing + restoring
_snapshot (show: boolean) {
const { model, runnablesStore } = this.props
if (show) {
runnablesStore.attemptingShowSnapshot = true
this._showTimeout = setTimeout(() => {
runnablesStore.showingSnapshot = true
this.props.events.emit('show:snapshot', model.testId, model.id)
}, 50)
} else {
runnablesStore.attemptingShowSnapshot = false
clearTimeout(this._showTimeout as TimeoutID)
setTimeout(() => {
// if we are currently showing a snapshot but
// we aren't trying to show a different snapshot
if (runnablesStore.showingSnapshot && !runnablesStore.attemptingShowSnapshot) {
runnablesStore.showingSnapshot = false
this.props.events.emit('hide:snapshot', model.testId, model.id)
}
}, 50)
}
}
}
export { Aliases, AliasesReferences, Message, Progress }
export default Command