-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
65 lines (54 loc) · 1.72 KB
/
index.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
const prettier = require('prettier');
const SYMBOL = Symbol('linaria-jest');
const CLASS_HTML_PATTERN = /class|className="([^"]+)"/;
const CLASS_CSS_PATTERN = /(css__.*) /g;
const classNamesMap = {};
let counter = 0xa0;
const getAllNodes = (node, nodes = []) => {
if (typeof node === 'object') {
nodes.push(node);
}
if (node.children) {
node.children.forEach(child => getAllNodes(child, nodes));
}
return nodes;
};
const markNodes = nodes =>
nodes.forEach(node => {
node[SYMBOL] = true; // eslint-disable-line no-param-reassign
});
const getCodeWithEnhancedClassNames = val => {
const styleSheet = document.querySelector('style').innerHTML;
let css = prettier.format(styleSheet, { parser: 'scss' });
let printedVal = val;
let match;
// eslint-disable-next-line no-cond-assign
while ((match = CLASS_CSS_PATTERN.exec(css))) {
classNamesMap[(counter++).toString(16)] = match[1];
}
Object.keys(classNamesMap).forEach(name => {
css = css.replace(new RegExp(classNamesMap[name], 'g'), name);
printedVal = printedVal.replace(new RegExp(classNamesMap[name], 'g'), name);
});
return { css, printedVal };
};
const reactSerializer = {
print: (val, print) => {
markNodes(getAllNodes(val));
const { css, printedVal } = getCodeWithEnhancedClassNames(print(val));
return `${css}${css ? '\n' : ''}${printedVal}`;
},
test: val =>
val && !val[SYMBOL] && val.$$typeof === Symbol.for('react.test.json'),
};
const preactSerializer = {
print: val => {
const { css, printedVal } = getCodeWithEnhancedClassNames(val);
return `${css}${css ? '\n' : ''}${printedVal}`;
},
test: val => val && CLASS_HTML_PATTERN.test(val),
};
module.exports = {
reactSerializer,
preactSerializer,
};