-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Utils.js
340 lines (288 loc) · 8.88 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
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
/* eslint no-use-before-define:0 */
import isEqual from 'lodash/isEqual';
import React from 'react';
import is from 'object-is';
import {
isDOMComponent,
findDOMNode,
childrenToArray,
} from './react-compat';
import {
REACT013,
REACT15,
} from './version';
function internalInstanceKey(node) {
return Object.keys(Object(node)).filter(key => key.match(/^__reactInternalInstance\$/))[0];
}
export function internalInstance(inst) {
return inst._reactInternalInstance ||
inst[internalInstanceKey(inst)];
}
export function isFunctionalComponent(inst) {
return inst && inst.constructor && inst.constructor.name === 'StatelessComponent';
}
export function propsOfNode(node) {
if (REACT013 && node && node._store) {
return (node._store.props) || {};
}
if (node && node._reactInternalComponent && node._reactInternalComponent._currentElement) {
return (node._reactInternalComponent._currentElement.props) || {};
}
if (node && node._currentElement) {
return (node._currentElement.props) || {};
}
if (REACT15 && node) {
if (internalInstance(node) && internalInstance(node)._currentElement) {
return (internalInstance(node)._currentElement.props) || {};
}
}
return (node && node.props) || {};
}
export function typeOfNode(node) {
return node ? node.type : null;
}
export function getNode(node) {
return isDOMComponent(node) ? findDOMNode(node) : node;
}
export function nodeHasType(node, type) {
if (!type || !node) return false;
if (!node.type) return false;
if (typeof node.type === 'string') return node.type === type;
return node.type.name === type || node.type.displayName === type;
}
export function childrenEqual(a, b, lenComp) {
if (a === b) return true;
if (!Array.isArray(a) && !Array.isArray(b)) {
return nodeEqual(a, b, lenComp);
}
if (!a && !b) return true;
if (a.length !== b.length) return false;
if (a.length === 0 && b.length === 0) return true;
for (let i = 0; i < a.length; i += 1) {
if (!nodeEqual(a[i], b[i], lenComp)) return false;
}
return true;
}
export function nodeEqual(a, b, lenComp = is) {
if (a === b) return true;
if (!a || !b) return false;
if (a.type !== b.type) return false;
const left = propsOfNode(a);
const leftKeys = Object.keys(left);
const right = propsOfNode(b);
for (let i = 0; i < leftKeys.length; i += 1) {
const prop = leftKeys[i];
// we will check children later
if (prop === 'children') {
// continue;
} else if (!(prop in right)) {
return false;
} else if (right[prop] === left[prop]) {
// continue;
} else if (typeof right[prop] === typeof left[prop] && typeof left[prop] === 'object') {
if (!isEqual(left[prop], right[prop])) return false;
} else {
return false;
}
}
const leftHasChildren = 'children' in left;
const rightHasChildren = 'children' in right;
if (leftHasChildren || rightHasChildren) {
if (!childrenEqual(
childrenToArray(left.children),
childrenToArray(right.children),
lenComp)) {
return false;
}
}
if (!isTextualNode(a)) {
const rightKeys = Object.keys(right);
return lenComp(leftKeys.length - leftHasChildren, rightKeys.length - rightHasChildren);
}
return false;
}
export function containsChildrenSubArray(match, node, subArray) {
const children = childrenOfNode(node);
const checker = (_, i) => arraysEqual(match, children.slice(i, i + subArray.length), subArray);
return children.some(checker);
}
function arraysEqual(match, left, right) {
return left.length === right.length && left.every((el, i) => match(el, right[i]));
}
function childrenOfNode(node) {
const props = propsOfNode(node);
const { children } = props;
return childrenToArray(children);
}
function isTextualNode(node) {
return typeof node === 'string' || typeof node === 'number';
}
export function isReactElementAlike(arg) {
return React.isValidElement(arg) || isTextualNode(arg) || Array.isArray(arg);
}
// 'click' => 'onClick'
// 'mouseEnter' => 'onMouseEnter'
export function propFromEvent(event) {
const nativeEvent = mapNativeEventNames(event);
return `on${nativeEvent[0].toUpperCase()}${nativeEvent.substring(1)}`;
}
export function withSetStateAllowed(fn) {
// NOTE(lmr):
// this is currently here to circumvent a React bug where `setState()` is
// not allowed without global being defined.
let cleanup = false;
if (typeof global.document === 'undefined') {
cleanup = true;
global.document = {};
}
fn();
if (cleanup) {
delete global.document;
}
}
export function splitSelector(selector) {
return selector.split(/(?=\.|\[.*\])|(?=#|\[#.*\])/);
}
const containsQuotes = /'|"/;
const containsColon = /:/;
export function isPseudoClassSelector(selector) {
if (containsColon.test(selector)) {
if (!containsQuotes.test(selector)) {
return true;
}
const tokens = selector.split(containsQuotes);
return tokens.some((token, i) =>
containsColon.test(token) && i % 2 === 0
);
}
return false;
}
export function selectorError(selector, type = '') {
return new TypeError(
`Enzyme received a ${type} CSS selector ('${selector}') that it does not currently support`
);
}
export const isCompoundSelector = /([a-z]\.[a-z]|[a-z]\[.*\]|[a-z]#[a-z])/i;
const isPropSelector = /^\[.*\]$/;
export const SELECTOR = {
CLASS_TYPE: 0,
ID_TYPE: 1,
PROP_TYPE: 2,
};
export function selectorType(selector) {
if (isPseudoClassSelector(selector)) {
throw selectorError(selector, 'pseudo-class');
}
if (selector[0] === '.') {
return SELECTOR.CLASS_TYPE;
} else if (selector[0] === '#') {
return SELECTOR.ID_TYPE;
} else if (isPropSelector.test(selector)) {
return SELECTOR.PROP_TYPE;
}
return undefined;
}
export function AND(fns) {
const fnsReversed = fns.slice().reverse();
return x => fnsReversed.every(fn => fn(x));
}
export function coercePropValue(propName, propValue) {
// can be undefined
if (propValue === undefined) {
return propValue;
}
// can be the empty string
if (propValue === '') {
return propValue;
}
if (propValue === 'NaN') {
return NaN;
}
if (propValue === 'null') {
return null;
}
const trimmedValue = propValue.trim();
// if propValue includes quotes, it should be
// treated as a string
if (/^(['"]).*\1$/.test(trimmedValue)) {
return trimmedValue.slice(1, -1);
}
const numericPropValue = +trimmedValue;
// if parseInt is not NaN, then we've wanted a number
if (!is(NaN, numericPropValue)) {
return numericPropValue;
}
// coerce to boolean
if (trimmedValue === 'true') return true;
if (trimmedValue === 'false') return false;
// user provided an unquoted string value
throw new TypeError(
`Enzyme::Unable to parse selector '[${propName}=${propValue}]'. ` +
`Perhaps you forgot to escape a string? Try '[${propName}="${trimmedValue}"]' instead.`
);
}
export function nodeHasProperty(node, propKey, stringifiedPropValue) {
const nodeProps = propsOfNode(node);
const descriptor = Object.getOwnPropertyDescriptor(nodeProps, propKey);
if (descriptor && descriptor.get) {
return false;
}
const nodePropValue = nodeProps[propKey];
const propValue = coercePropValue(propKey, stringifiedPropValue);
if (nodePropValue === undefined) {
return false;
}
if (propValue !== undefined) {
return is(nodePropValue, propValue);
}
return Object.prototype.hasOwnProperty.call(nodeProps, propKey);
}
export function mapNativeEventNames(event) {
const nativeToReactEventMap = {
compositionend: 'compositionEnd',
compositionstart: 'compositionStart',
compositionupdate: 'compositionUpdate',
keydown: 'keyDown',
keyup: 'keyUp',
keypress: 'keyPress',
contextmenu: 'contextMenu',
dblclick: 'doubleClick',
doubleclick: 'doubleClick', // kept for legacy. TODO: remove with next major.
dragend: 'dragEnd',
dragenter: 'dragEnter',
dragexist: 'dragExit',
dragleave: 'dragLeave',
dragover: 'dragOver',
dragstart: 'dragStart',
mousedown: 'mouseDown',
mousemove: 'mouseMove',
mouseout: 'mouseOut',
mouseover: 'mouseOver',
mouseup: 'mouseUp',
touchcancel: 'touchCancel',
touchend: 'touchEnd',
touchmove: 'touchMove',
touchstart: 'touchStart',
canplay: 'canPlay',
canplaythrough: 'canPlayThrough',
durationchange: 'durationChange',
loadeddata: 'loadedData',
loadedmetadata: 'loadedMetadata',
loadstart: 'loadStart',
ratechange: 'rateChange',
timeupdate: 'timeUpdate',
volumechange: 'volumeChange',
};
if (!REACT013) {
// these could not be simulated in React 0.13:
// https://github.com/facebook/react/issues/1297
nativeToReactEventMap.mouseenter = 'mouseEnter';
nativeToReactEventMap.mouseleave = 'mouseLeave';
}
return nativeToReactEventMap[event] || event;
}
export function displayNameOfNode(node) {
const { type } = node;
if (!type) return null;
return type.displayName || type.name || type;
}