-
Notifications
You must be signed in to change notification settings - Fork 0
/
style-manager.js
308 lines (281 loc) · 11.3 KB
/
style-manager.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
const {Emitter, Disposable} = require('event-kit')
const crypto = require('crypto')
const fs = require('fs-plus')
const path = require('path')
const postcss = require('postcss')
const selectorParser = require('postcss-selector-parser')
const StylesElement = require('./styles-element')
const DEPRECATED_SYNTAX_SELECTORS = require('./deprecated-syntax-selectors')
// Extended: A singleton instance of this class available via `atom.styles`,
// which you can use to globally query and observe the set of active style
// sheets. The `StyleManager` doesn't add any style elements to the DOM on its
// own, but is instead subscribed to by individual `<atom-styles>` elements,
// which clone and attach style elements in different contexts.
module.exports = class StyleManager {
constructor ({configDirPath}) {
this.configDirPath = configDirPath
if (this.configDirPath != null) {
this.cacheDirPath = path.join(this.configDirPath, 'compile-cache', 'style-manager')
}
this.emitter = new Emitter()
this.styleElements = []
this.styleElementsBySourcePath = {}
this.deprecationsBySourcePath = {}
}
/*
Section: Event Subscription
*/
// Extended: Invoke `callback` for all current and future style elements.
//
// * `callback` {Function} that is called with style elements.
// * `styleElement` An `HTMLStyleElement` instance. The `.sheet` property
// will be null because this element isn't attached to the DOM. If you want
// to attach this element to the DOM, be sure to clone it first by calling
// `.cloneNode(true)` on it. The style element will also have the following
// non-standard properties:
// * `sourcePath` A {String} containing the path from which the style
// element was loaded.
// * `context` A {String} indicating the target context of the style
// element.
//
// Returns a {Disposable} on which `.dispose()` can be called to cancel the
// subscription.
observeStyleElements (callback) {
for (let styleElement of this.getStyleElements()) {
callback(styleElement)
}
return this.onDidAddStyleElement(callback)
}
// Extended: Invoke `callback` when a style element is added.
//
// * `callback` {Function} that is called with style elements.
// * `styleElement` An `HTMLStyleElement` instance. The `.sheet` property
// will be null because this element isn't attached to the DOM. If you want
// to attach this element to the DOM, be sure to clone it first by calling
// `.cloneNode(true)` on it. The style element will also have the following
// non-standard properties:
// * `sourcePath` A {String} containing the path from which the style
// element was loaded.
// * `context` A {String} indicating the target context of the style
// element.
//
// Returns a {Disposable} on which `.dispose()` can be called to cancel the
// subscription.
onDidAddStyleElement (callback) {
return this.emitter.on('did-add-style-element', callback)
}
// Extended: Invoke `callback` when a style element is removed.
//
// * `callback` {Function} that is called with style elements.
// * `styleElement` An `HTMLStyleElement` instance.
//
// Returns a {Disposable} on which `.dispose()` can be called to cancel the
// subscription.
onDidRemoveStyleElement (callback) {
return this.emitter.on('did-remove-style-element', callback)
}
// Extended: Invoke `callback` when an existing style element is updated.
//
// * `callback` {Function} that is called with style elements.
// * `styleElement` An `HTMLStyleElement` instance. The `.sheet` property
// will be null because this element isn't attached to the DOM. The style
// element will also have the following non-standard properties:
// * `sourcePath` A {String} containing the path from which the style
// element was loaded.
// * `context` A {String} indicating the target context of the style
// element.
//
// Returns a {Disposable} on which `.dispose()` can be called to cancel the
// subscription.
onDidUpdateStyleElement (callback) {
return this.emitter.on('did-update-style-element', callback)
}
onDidUpdateDeprecations (callback) {
return this.emitter.on('did-update-deprecations', callback)
}
/*
Section: Reading Style Elements
*/
// Extended: Get all loaded style elements.
getStyleElements () {
return this.styleElements.slice()
}
addStyleSheet (source, params = {}) {
let styleElement
let updated
if (params.sourcePath != null && this.styleElementsBySourcePath[params.sourcePath] != null) {
updated = true
styleElement = this.styleElementsBySourcePath[params.sourcePath]
} else {
updated = false
styleElement = document.createElement('style')
if (params.sourcePath != null) {
styleElement.sourcePath = params.sourcePath
styleElement.setAttribute('source-path', params.sourcePath)
}
if (params.context != null) {
styleElement.context = params.context
styleElement.setAttribute('context', params.context)
}
if (params.priority != null) {
styleElement.priority = params.priority
styleElement.setAttribute('priority', params.priority)
}
}
let transformed
if (this.cacheDirPath != null) {
const hash = crypto.createHash('sha1')
if (params.context != null) {
hash.update(params.context)
}
hash.update(source)
const cacheFilePath = path.join(this.cacheDirPath, hash.digest('hex'))
try {
transformed = JSON.parse(fs.readFileSync(cacheFilePath))
} catch (e) {
transformed = transformDeprecatedShadowDOMSelectors(source, params.context)
fs.writeFileSync(cacheFilePath, JSON.stringify(transformed))
}
} else {
transformed = transformDeprecatedShadowDOMSelectors(source, params.context)
}
styleElement.textContent = transformed.source
if (transformed.deprecationMessage) {
this.deprecationsBySourcePath[params.sourcePath] = {message: transformed.deprecationMessage}
this.emitter.emit('did-update-deprecations')
}
if (updated) {
this.emitter.emit('did-update-style-element', styleElement)
} else {
this.addStyleElement(styleElement)
}
return new Disposable(() => { this.removeStyleElement(styleElement) })
}
addStyleElement (styleElement) {
let insertIndex = this.styleElements.length
if (styleElement.priority != null) {
for (let [index, existingElement] of this.styleElements.entries()) {
if (existingElement.priority > styleElement.priority) {
insertIndex = index
break
}
}
}
this.styleElements.splice(insertIndex, 0, styleElement)
if (styleElement.sourcePath != null && this.styleElementsBySourcePath[styleElement.sourcePath] == null) {
this.styleElementsBySourcePath[styleElement.sourcePath] = styleElement
}
this.emitter.emit('did-add-style-element', styleElement)
}
removeStyleElement (styleElement) {
const index = this.styleElements.indexOf(styleElement)
if (index !== -1) {
this.styleElements.splice(index, 1)
if (styleElement.sourcePath != null) {
delete this.styleElementsBySourcePath[styleElement.sourcePath]
}
this.emitter.emit('did-remove-style-element', styleElement)
}
}
getDeprecations () {
return this.deprecationsBySourcePath
}
clearDeprecations () {
this.deprecationsBySourcePath = {}
}
getSnapshot () {
return this.styleElements.slice()
}
restoreSnapshot (styleElementsToRestore) {
for (let styleElement of this.getStyleElements()) {
if (!styleElementsToRestore.includes(styleElement)) {
this.removeStyleElement(styleElement)
}
}
const existingStyleElements = this.getStyleElements()
for (let styleElement of styleElementsToRestore) {
if (!existingStyleElements.includes(styleElement)) {
this.addStyleElement(styleElement)
}
}
}
buildStylesElement () {
var stylesElement = new StylesElement()
stylesElement.initialize(this)
return stylesElement
}
/*
Section: Paths
*/
// Extended: Get the path of the user style sheet in `~/.atom`.
//
// Returns a {String}.
getUserStyleSheetPath () {
if (this.configDirPath == null) {
return ''
} else {
const stylesheetPath = fs.resolve(path.join(this.configDirPath, 'styles'), ['css', 'less'])
if (fs.isFileSync(stylesheetPath)) {
return stylesheetPath
} else {
return path.join(this.configDirPath, 'styles.less')
}
}
}
}
function transformDeprecatedShadowDOMSelectors (css, context) {
const transformedSelectors = []
const transformedSource = postcss.parse(css)
transformedSource.walkRules((rule) => {
const transformedSelector = selectorParser((selectors) => {
selectors.each((selector) => {
const firstNode = selector.nodes[0]
if (context === 'atom-text-editor' && firstNode.type === 'pseudo' && firstNode.value === ':host') {
const atomTextEditorElementNode = selectorParser.tag({value: 'atom-text-editor'})
firstNode.replaceWith(atomTextEditorElementNode)
}
let previousNodeIsAtomTextEditor = false
let targetsAtomTextEditorShadow = context === 'atom-text-editor'
let previousNode
selector.each((node) => {
if (targetsAtomTextEditorShadow && node.type === 'class') {
if (DEPRECATED_SYNTAX_SELECTORS.has(node.value)) {
node.value = `syntax--${node.value}`
}
} else {
if (previousNodeIsAtomTextEditor && node.type === 'pseudo' && node.value === '::shadow') {
node.type = 'className'
node.value = '.editor'
targetsAtomTextEditorShadow = true
}
}
previousNode = node
if (node.type === 'combinator') {
previousNodeIsAtomTextEditor = false
} else if (previousNode.type === 'tag' && previousNode.value === 'atom-text-editor') {
previousNodeIsAtomTextEditor = true
}
})
})
}).process(rule.selector, {lossless: true}).result
if (transformedSelector !== rule.selector) {
transformedSelectors.push({before: rule.selector, after: transformedSelector})
rule.selector = transformedSelector
}
})
let deprecationMessage
if (transformedSelectors.length > 0) {
deprecationMessage = 'Starting from Atom v1.13.0, the contents of `atom-text-editor` elements '
deprecationMessage += 'are no longer encapsulated within a shadow DOM boundary. '
deprecationMessage += 'This means you should stop using `:host` and `::shadow` '
deprecationMessage += 'pseudo-selectors, and prepend all your syntax selectors with `syntax--`. '
deprecationMessage += 'To prevent breakage with existing style sheets, Atom will automatically '
deprecationMessage += 'upgrade the following selectors:\n\n'
deprecationMessage += transformedSelectors
.map((selector) => `* \`${selector.before}\` => \`${selector.after}\``)
.join('\n\n') + '\n\n'
deprecationMessage += 'Automatic translation of selectors will be removed in a few release cycles to minimize startup time. '
deprecationMessage += 'Please, make sure to upgrade the above selectors as soon as possible.'
}
return {source: transformedSource.toString(), deprecationMessage}
}