-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathutils.js
343 lines (295 loc) Β· 9.26 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
341
342
343
const insertedRules = new WeakMap()
if (typeof CSSStyleSheet !== 'undefined') {
const insertRule = CSSStyleSheet.prototype.insertRule
CSSStyleSheet.prototype.insertRule = function (...args) {
let sheetRules = insertedRules.get(this)
if (!sheetRules) {
sheetRules = []
insertedRules.set(this, sheetRules)
}
const rule = args[0]
sheetRules.push(rule)
return insertRule.apply(this, args)
}
}
const isBrowser = typeof document !== 'undefined'
function last(arr) {
return arr.length > 0 ? arr[arr.length - 1] : undefined
}
export function flatMap /* <T, S> */(
arr /*: T[] */,
iteratee /*: (arg: T) => S[] | S */
) /*: S[] */ {
return [].concat(...arr.map(iteratee))
}
export function findLast /* <T> */(
arr /*: T[] */,
predicate /*: T => boolean */
) {
for (let i = arr.length - 1; i >= 0; i--) {
if (predicate(arr[i])) {
return arr[i]
}
}
}
export function findIndexFrom /* <T> */(
arr /*: T[] */,
fromIndex /*: number */,
predicate /*: T => boolean */
) {
for (let i = fromIndex; i < arr.length; i++) {
if (predicate(arr[i])) {
return i
}
}
return -1
}
function getClassNames(selectors, classes /* ?: string */) {
return classes ? selectors.concat(classes.split(' ')) : selectors
}
function getClassNamesFromTestRenderer(selectors, { props = {} }) {
return getClassNames(selectors, props.className || props.class)
}
function shouldDive(node) {
return typeof node.dive === 'function' && typeof node.type() !== 'string'
}
function isTagWithClassName(node) {
return node.prop('className') && typeof node.type() === 'string'
}
function findNodeWithClassName(node) {
// Find the first node with a className prop
const found = node.findWhere(isTagWithClassName)
return found.length ? found.first() : null
}
function getClassNameProp(node) {
return (node && node.prop('className')) || ''
}
export function unwrapFromPotentialFragment(node) {
if (node.type() === Symbol.for('react.fragment')) {
const isShallow = !!node.dive
if (isShallow) {
// render the `<Insertion/>` so it has a chance to insert rules in the JSDOM
node.children().first().dive()
}
return node.children().last()
}
return node
}
function getClassNamesFromCheerio(selectors, node) {
const classes = node.attr('class')
return getClassNames(selectors, classes)
}
function getClassNamesFromDOMElement(selectors, node) {
return getClassNames(selectors, node.getAttribute('class'))
}
export function isReactElement(val) /*: boolean */ {
return (
val.$$typeof === Symbol.for('react.test.json') ||
val.$$typeof === Symbol.for('react.element')
)
}
export function isEmotionCssPropElementType(val) /*: boolean */ {
return (
val.$$typeof === Symbol.for('react.element') &&
val.type.displayName === 'EmotionCssPropInternal'
)
}
export function isStyledElementType(val /* : any */) /* : boolean */ {
if (val.$$typeof !== Symbol.for('react.element')) {
return false
}
const { type } = val
return type.__emotion_real === type
}
const domElementPattern = /^((HTML|SVG)\w*)?Element$/
export function isDOMElement(val) /*: boolean */ {
return (
val.nodeType === 1 &&
val.constructor &&
val.constructor.name &&
domElementPattern.test(val.constructor.name)
)
}
function isCheerioElement(val) /*: boolean */ {
return val.cheerio === '[cheerio object]'
}
export function getClassNamesFromNodes(nodes /*: Array<any> */) {
return nodes.reduce((selectors, node) => {
if (isCheerioElement(node)) {
return getClassNamesFromCheerio(selectors, node)
} else if (isReactElement(node)) {
return getClassNamesFromTestRenderer(selectors, node)
}
return getClassNamesFromDOMElement(selectors, node)
}, [])
}
const keyframesPattern = /^@keyframes\s+(animation-[^{\s]+)+/
const removeCommentPattern = /\/\*[\s\S]*?\*\//g
const getElementRules = (element /*: HTMLStyleElement */) /*: string[] */ => {
const nonSpeedyRule = element.textContent
if (nonSpeedyRule) {
return [nonSpeedyRule]
}
if (!element.sheet) {
return []
}
const rules = insertedRules.get(element.sheet)
if (rules) {
return rules
}
return [].slice.call(element.sheet.cssRules).map(cssRule => cssRule.cssText)
}
const getKeyframesMap = rules =>
rules.reduce((keyframes, rule) => {
const match = rule.match(keyframesPattern)
if (match !== null) {
const name = match[1]
if (keyframes[name] === undefined) {
keyframes[name] = ''
}
keyframes[name] += rule
}
return keyframes
}, {})
export function getStylesFromClassNames(
classNames /*: Array<string> */,
elements /*: Array<HTMLStyleElement> */
) /*: string */ {
if (!classNames.length) {
return ''
}
const keys = getKeys(elements)
if (!keys.length) {
return ''
}
const targetClassName = classNames.find(className =>
/^e[a-z0-9]+$/.test(className)
)
const keyPattern = `(${keys.join('|')})-`
const classNamesRegExp = new RegExp(
targetClassName ? `^(${keyPattern}|${targetClassName})` : `^${keyPattern}`
)
const filteredClassNames = classNames.filter(className =>
classNamesRegExp.test(className)
)
if (!filteredClassNames.length) {
return ''
}
const selectorPattern = new RegExp(
'\\.(?:' + filteredClassNames.map(cls => `(${cls})`).join('|') + ')'
)
const rules = flatMap(elements, getElementRules)
let styles = rules
.map((rule /*: string */) => {
const match = rule.match(selectorPattern)
if (!match) {
return null
}
// `selectorPattern` represents all emotion-generated class names
// each possible class name is wrapped in a capturing group
// and those groups appear in the same order as they appear in the DOM within class attributes
// because we've gathered them from the DOM in such order
// given that information we can sort matched rules based on the capturing group that has been matched
// to end up with styles in a stable order
const matchedCapturingGroupIndex = findIndexFrom(match, 1, Boolean)
return [rule, matchedCapturingGroupIndex]
})
.filter(Boolean)
.sort(
([ruleA, classNameIndexA], [ruleB, classNameIndexB]) =>
classNameIndexA - classNameIndexB
)
.map(([rule]) => rule)
.join('')
const keyframesMap = getKeyframesMap(rules)
const keyframeNameKeys = Object.keys(keyframesMap)
let keyframesStyles = ''
if (keyframeNameKeys.length) {
const keyframesNamePattern = new RegExp(keyframeNameKeys.join('|'), 'g')
const keyframesNameCache = {}
let index = 0
styles = styles.replace(keyframesNamePattern, name => {
if (keyframesNameCache[name] === undefined) {
keyframesNameCache[name] = `animation-${index++}`
keyframesStyles += keyframesMap[name]
}
return keyframesNameCache[name]
})
keyframesStyles = keyframesStyles.replace(keyframesNamePattern, value => {
return keyframesNameCache[value]
})
}
return (keyframesStyles + styles).replace(removeCommentPattern, '')
}
export function getStyleElements() /*: Array<HTMLStyleElement> */ {
if (!isBrowser) {
throw new Error(
'jest-emotion requires jsdom. See https://jestjs.io/docs/en/configuration#testenvironment-string for more information.'
)
}
const elements1 = Array.from(document.querySelectorAll('style[data-emotion]'))
const elements2 = Array.from(
document.querySelectorAll('style[data-precedence^=emotion-]')
)
return elements1.concat(elements2)
}
const unique = arr => Array.from(new Set(arr))
export function getKeys(elements /*: Array<HTMLStyleElement> */) {
const keys = unique(
elements.map(element => {
const dataEmotion = element.getAttribute('data-emotion')
if (dataEmotion) {
return dataEmotion.split(' ')[0]
}
const dataPrecedence = element.getAttribute('data-precedence')
if (dataPrecedence?.startsWith('emotion-')) {
return dataPrecedence.replace('emotion-', '')
}
return null
})
).filter(Boolean)
return keys
}
export function hasClassNames(
classNames /*: Array<string> */,
selectors /*: Array<string> */,
target /* ?: string | RegExp */
) /*: boolean */ {
// selectors is the classNames of specific css rule
return selectors.some(selector => {
// if no target, use className of the specific css rule and try to find it
// in the list of received node classNames to make sure this css rule
// applied for root element
if (!target) {
const lastCls = last(selector.split(' '))
if (!lastCls) {
return false
}
return classNames.includes(lastCls.slice(1))
}
// check if selector (className) of specific css rule match target
return target instanceof RegExp
? target.test(selector)
: selector.includes(target)
})
}
export function getMediaRules(
rules /*: Array<Object> */,
media /*: string */
) /*: Array<any> */ {
return flatMap(
rules.filter(rule => {
if (rule.type !== '@media') {
return false
}
return rule.value.replace(/\s/g, '').includes(media.replace(/\s/g, ''))
}),
media => media.children
)
}
export function isPrimitive(test) {
return test !== Object(test)
}
export function hasIntersection(left /* any[] */, right /* any[] */) {
return left.some(value => right.includes(value))
}