-
Notifications
You must be signed in to change notification settings - Fork 262
/
stylesheet-registry.js
219 lines (188 loc) · 5.47 KB
/
stylesheet-registry.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
import hashString from 'string-hash'
import DefaultStyleSheet from './lib/stylesheet'
const sanitize = rule => rule.replace(/\/style/gi, '\\/style')
export default class StyleSheetRegistry {
constructor({
styleSheet = null,
optimizeForSpeed = false,
isBrowser = typeof window !== 'undefined'
} = {}) {
this._sheet =
styleSheet ||
new DefaultStyleSheet({
name: 'styled-jsx',
optimizeForSpeed
})
this._sheet.inject()
if (styleSheet && typeof optimizeForSpeed === 'boolean') {
this._sheet.setOptimizeForSpeed(optimizeForSpeed)
this._optimizeForSpeed = this._sheet.isOptimizeForSpeed()
}
this._isBrowser = isBrowser
this._fromServer = undefined
this._indices = {}
this._instancesCounts = {}
this.computeId = this.createComputeId()
this.computeSelector = this.createComputeSelector()
}
add(props) {
if (undefined === this._optimizeForSpeed) {
this._optimizeForSpeed = Array.isArray(props.children)
this._sheet.setOptimizeForSpeed(this._optimizeForSpeed)
this._optimizeForSpeed = this._sheet.isOptimizeForSpeed()
}
if (this._isBrowser && !this._fromServer) {
this._fromServer = this.selectFromServer()
this._instancesCounts = Object.keys(this._fromServer).reduce(
(acc, tagName) => {
acc[tagName] = 0
return acc
},
{}
)
}
const { styleId, rules } = this.getIdAndRules(props)
// Deduping: just increase the instances count.
if (styleId in this._instancesCounts) {
this._instancesCounts[styleId] += 1
return
}
const indices = rules
.map(rule => this._sheet.insertRule(rule))
// Filter out invalid rules
.filter(index => index !== -1)
this._indices[styleId] = indices
this._instancesCounts[styleId] = 1
}
remove(props) {
const { styleId } = this.getIdAndRules(props)
invariant(
styleId in this._instancesCounts,
`styleId: \`${styleId}\` not found`
)
this._instancesCounts[styleId] -= 1
if (this._instancesCounts[styleId] < 1) {
const tagFromServer = this._fromServer && this._fromServer[styleId]
if (tagFromServer) {
tagFromServer.parentNode.removeChild(tagFromServer)
delete this._fromServer[styleId]
} else {
this._indices[styleId].forEach(index => this._sheet.deleteRule(index))
delete this._indices[styleId]
}
delete this._instancesCounts[styleId]
}
}
update(props, nextProps) {
this.add(nextProps)
this.remove(props)
}
flush() {
this._sheet.flush()
this._sheet.inject()
this._fromServer = undefined
this._indices = {}
this._instancesCounts = {}
this.computeId = this.createComputeId()
this.computeSelector = this.createComputeSelector()
}
cssRules() {
const fromServer = this._fromServer
? Object.keys(this._fromServer).map(styleId => [
styleId,
this._fromServer[styleId]
])
: []
const cssRules = this._sheet.cssRules()
return fromServer.concat(
Object.keys(this._indices)
.map(styleId => [
styleId,
this._indices[styleId]
.map(index => cssRules[index].cssText)
.join(this._optimizeForSpeed ? '' : '\n')
])
// filter out empty rules
.filter(rule => Boolean(rule[1]))
)
}
/**
* createComputeId
*
* Creates a function to compute and memoize a jsx id from a basedId and optionally props.
*/
createComputeId() {
const cache = {}
return function(baseId, props) {
if (!props) {
return `jsx-${baseId}`
}
const propsToString = String(props)
const key = baseId + propsToString
// return `jsx-${hashString(`${baseId}-${propsToString}`)}`
if (!cache[key]) {
cache[key] = `jsx-${hashString(`${baseId}-${propsToString}`)}`
}
return cache[key]
}
}
/**
* createComputeSelector
*
* Creates a function to compute and memoize dynamic selectors.
*/
createComputeSelector(
selectoPlaceholderRegexp = /__jsx-style-dynamic-selector/g
) {
const cache = {}
return function(id, css) {
// Sanitize SSR-ed CSS.
// Client side code doesn't need to be sanitized since we use
// document.createTextNode (dev) and the CSSOM api sheet.insertRule (prod).
if (!this._isBrowser) {
css = sanitize(css)
}
const idcss = id + css
if (!cache[idcss]) {
cache[idcss] = css.replace(selectoPlaceholderRegexp, id)
}
return cache[idcss]
}
}
getIdAndRules(props) {
const { children: css, dynamic, id } = props
if (dynamic) {
const styleId = this.computeId(id, dynamic)
return {
styleId,
rules: Array.isArray(css)
? css.map(rule => this.computeSelector(styleId, rule))
: [this.computeSelector(styleId, css)]
}
}
return {
styleId: this.computeId(id),
rules: Array.isArray(css) ? css : [css]
}
}
/**
* selectFromServer
*
* Collects style tags from the document with id __jsx-XXX
*/
selectFromServer() {
const elements = Array.prototype.slice.call(
document.querySelectorAll('[id^="__jsx-"]')
)
return elements.reduce((acc, element) => {
const id = element.id.slice(2)
acc[id] = element
return acc
}, {})
}
}
function invariant(condition, message) {
if (!condition) {
throw new Error(`StyleSheetRegistry: ${message}.`)
}
}