-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathutils.js
254 lines (224 loc) · 6 KB
/
utils.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
import redent from 'redent'
import {parse} from '@adobe/css-tools'
class GenericTypeError extends Error {
constructor(expectedString, received, matcherFn, context) {
super()
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, matcherFn)
}
let withType = ''
try {
withType = context.utils.printWithType(
'Received',
received,
context.utils.printReceived,
)
} catch (e) {
// Can throw for Document:
// https://github.com/jsdom/jsdom/issues/2304
}
this.message = [
context.utils.matcherHint(
`${context.isNot ? '.not' : ''}.${matcherFn.name}`,
'received',
'',
),
'',
// eslint-disable-next-line new-cap
`${context.utils.RECEIVED_COLOR(
'received',
)} value must ${expectedString}.`,
withType,
].join('\n')
}
}
class HtmlElementTypeError extends GenericTypeError {
constructor(...args) {
super('be an HTMLElement or an SVGElement', ...args)
}
}
class NodeTypeError extends GenericTypeError {
constructor(...args) {
super('be a Node', ...args)
}
}
function checkHasWindow(htmlElement, ErrorClass, ...args) {
if (
!htmlElement ||
!htmlElement.ownerDocument ||
!htmlElement.ownerDocument.defaultView
) {
throw new ErrorClass(htmlElement, ...args)
}
}
function checkNode(node, ...args) {
checkHasWindow(node, NodeTypeError, ...args)
const window = node.ownerDocument.defaultView
if (!(node instanceof window.Node)) {
throw new NodeTypeError(node, ...args)
}
}
function checkHtmlElement(htmlElement, ...args) {
checkHasWindow(htmlElement, HtmlElementTypeError, ...args)
const window = htmlElement.ownerDocument.defaultView
if (
!(htmlElement instanceof window.HTMLElement) &&
!(htmlElement instanceof window.SVGElement)
) {
throw new HtmlElementTypeError(htmlElement, ...args)
}
}
class InvalidCSSError extends Error {
constructor(received, matcherFn, context) {
super()
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, matcherFn)
}
this.message = [
received.message,
'',
// eslint-disable-next-line new-cap
context.utils.RECEIVED_COLOR(`Failing css:`),
// eslint-disable-next-line new-cap
context.utils.RECEIVED_COLOR(`${received.css}`),
].join('\n')
}
}
function parseCSS(css, ...args) {
const ast = parse(`selector { ${css} }`, {silent: true}).stylesheet
if (ast.parsingErrors && ast.parsingErrors.length > 0) {
const {reason, line} = ast.parsingErrors[0]
throw new InvalidCSSError(
{
css,
message: `Syntax error parsing expected css: ${reason} on line: ${line}`,
},
...args,
)
}
const parsedRules = ast.rules[0].declarations
.filter(d => d.type === 'declaration')
.reduce(
(obj, {property, value}) => Object.assign(obj, {[property]: value}),
{},
)
return parsedRules
}
function display(context, value) {
return typeof value === 'string' ? value : context.utils.stringify(value)
}
function getMessage(
context,
matcher,
expectedLabel,
expectedValue,
receivedLabel,
receivedValue,
) {
return [
`${matcher}\n`,
// eslint-disable-next-line new-cap
`${expectedLabel}:\n${context.utils.EXPECTED_COLOR(
redent(display(context, expectedValue), 2),
)}`,
// eslint-disable-next-line new-cap
`${receivedLabel}:\n${context.utils.RECEIVED_COLOR(
redent(display(context, receivedValue), 2),
)}`,
].join('\n')
}
function matches(textToMatch, matcher) {
if (matcher instanceof RegExp) {
return matcher.test(textToMatch)
} else {
return textToMatch.includes(String(matcher))
}
}
function deprecate(name, replacementText) {
// Notify user that they are using deprecated functionality.
// eslint-disable-next-line no-console
console.warn(
`Warning: ${name} has been deprecated and will be removed in future updates.`,
replacementText,
)
}
function normalize(text) {
return text.replace(/\s+/g, ' ').trim()
}
function getTag(element) {
return element.tagName && element.tagName.toLowerCase()
}
function getSelectValue({multiple, options}) {
const selectedOptions = [...options].filter(option => option.selected)
if (multiple) {
return [...selectedOptions].map(opt => opt.value)
}
/* istanbul ignore if */
if (selectedOptions.length === 0) {
return undefined // Couldn't make this happen, but just in case
}
return selectedOptions[0].value
}
function getInputValue(inputElement) {
switch (inputElement.type) {
case 'number':
return inputElement.value === '' ? null : Number(inputElement.value)
case 'checkbox':
return inputElement.checked
default:
return inputElement.value
}
}
const rolesSupportingValues = ['meter', 'progressbar', 'slider', 'spinbutton']
function getAccessibleValue(element) {
if (!rolesSupportingValues.includes(element.getAttribute('role'))) {
return undefined
}
return Number(element.getAttribute('aria-valuenow'))
}
function getSingleElementValue(element) {
/* istanbul ignore if */
if (!element) {
return undefined
}
switch (element.tagName.toLowerCase()) {
case 'input':
return getInputValue(element)
case 'select':
return getSelectValue(element)
default: {
return element.value ?? getAccessibleValue(element)
}
}
}
function toSentence(
array,
{wordConnector = ', ', lastWordConnector = ' and '} = {},
) {
return [array.slice(0, -1).join(wordConnector), array[array.length - 1]].join(
array.length > 1 ? lastWordConnector : '',
)
}
function compareArraysAsSet(arr1, arr2) {
if (Array.isArray(arr1) && Array.isArray(arr2)) {
return [...new Set(arr1)].every(v => new Set(arr2).has(v))
}
return undefined
}
export {
HtmlElementTypeError,
NodeTypeError,
checkHtmlElement,
checkNode,
parseCSS,
deprecate,
getMessage,
matches,
normalize,
getTag,
getSingleElementValue,
toSentence,
compareArraysAsSet,
}