/
component.js
117 lines (97 loc) · 2.7 KB
/
component.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
'use strict'
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "h" }] */
const { h, Indent, Component, Text } = require('ink')
const { reduce, map } = require('lodash')
const chalk = require('chalk')
const os = require('os')
const { getStatusColor } = require('./helpers')
module.exports = class Counter extends Component {
constructor (props) {
super(props)
this.state = {
count: {},
links: {}
}
const { emitter } = props
emitter.on('*', (eventName, data) => {
if (eventName !== 'end') this.addStatusCode(eventName, data)
else this.setState({ end: true })
})
}
addStatusCode (statusCode, payload) {
const status = this.state.count[statusCode]
const links = this.state.links[statusCode]
const linkItem = [payload.statusCode, payload.url]
let nextCount
let nextLinks
if (status === undefined) {
nextCount = { [statusCode]: 1 }
} else {
nextCount = { [statusCode]: status + 1 }
}
if (links === undefined) {
nextLinks = { [statusCode]: [linkItem] }
} else {
nextLinks = { [statusCode]: links.concat([linkItem]) }
}
this.setState({
count: { ...this.state.count, ...nextCount },
links: { ...this.state.links, ...nextLinks }
})
}
printStatusCode (statusCode, count) {
return (
<Indent size={1}>
<Text hex={getStatusColor(statusCode)}>
· {statusCode} {count}
</Text>
</Indent>
)
}
printUrl (statusCode, url) {
const prettyStatusCode = chalk.hex(getStatusColor(statusCode))(statusCode)
const prettyUrl = chalk.gray(url)
return ` ${prettyStatusCode} ${prettyUrl}`
}
renderStatusCode (status) {
return map(status, (count, stat) => (
<div>{this.printStatusCode(stat, count)}</div>
))
}
renderLinks (status, links) {
const total = reduce(status, (acc, count) => acc + count, 0)
const details = map(status, (count, stat) => {
const urls = map(links[stat], ([statusCode, url]) =>
this.printUrl(statusCode, url)
).join(os.EOL)
return (
<span>
<div>{this.printStatusCode(stat, count)}</div>
<div>
{urls}
<div />
</div>
</span>
)
})
return (
<span>
<div>{details}</div>
<span>
<Indent size={3}>{chalk.gray(`Total ${total}`)}</Indent>
</span>
</span>
)
}
render () {
return (
<span>
{!this.state.end
? this.renderStatusCode(this.state.count)
: this.props.minimal
? this.renderStatusCode(this.state.count)
: this.renderLinks(this.state.count, this.state.links)}
</span>
)
}
}