/
style-transform.js
116 lines (98 loc) · 2.35 KB
/
style-transform.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
import Stylis from 'stylis'
import stylisRuleSheet from 'stylis-rule-sheet'
const stylis = new Stylis()
function disableNestingPlugin(...args) {
let [context, , , parent = [], line, column] = args
if (context === 2) {
// replace null characters and trim
// eslint-disable-next-line no-control-regex
parent = (parent[0] || '').replace(/\u0000/g, '').trim()
if (parent.length > 0 && parent.charAt(0) !== '@') {
throw new Error(
`Nesting detected at ${line}:${column}. ` +
'Unfortunately nesting is not supported by styled-jsx.'
)
}
}
}
let generator
let filename
let offset
function sourceMapsPlugin(...args) {
const [context, , , , line, column, length] = args
// Pre-processed, init source map
if (context === -1 && generator !== undefined) {
generator.addMapping({
generated: {
line: 1,
column: 0
},
source: filename,
original: offset
})
return
}
// Post-processed
if (context === -2 && generator !== undefined) {
generator = undefined
offset = undefined
filename = undefined
return
}
// Selector/property, update source map
if ((context === 1 || context === 2) && generator !== undefined) {
generator.addMapping({
generated: {
line: 1,
column: length
},
source: filename,
original: {
line: line + offset.line,
column: column + offset.column
}
})
}
}
/**
* splitRulesPlugin
* Used to split a blob of css into an array of rules
* that can inserted via sheet.insertRule
*/
let splitRules = []
const splitRulesPlugin = stylisRuleSheet(rule => {
splitRules.push(rule)
})
stylis.use(disableNestingPlugin)
stylis.use(sourceMapsPlugin)
stylis.use(splitRulesPlugin)
stylis.set({
cascade: false,
compress: true
})
/**
* Public transform function
*
* @param {String} hash
* @param {String} styles
* @param {Object} settings
* @return {string}
*/
function transform(hash, styles, settings = {}) {
generator = settings.generator
offset = settings.offset
filename = settings.filename
splitRules = []
stylis.set({
prefix:
typeof settings.vendorPrefixes === 'boolean'
? settings.vendorPrefixes
: true
})
stylis(hash, styles)
if (settings.splitRules) {
return splitRules
}
return splitRules.join('')
}
export default transform