-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcss-variables.js
318 lines (251 loc) · 8.23 KB
/
css-variables.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
//[css-variables]
function analyzeVariables() {
const PREFIX = "almanac-var2020-";
// Selector to find elements that are relevant to the graph
const selector = `.${PREFIX}element, [style*="--"]`;
// Extract a list of custom properties set by a value
function extractValueProperties(value) {
// https://drafts.csswg.org/css-syntax-3/#ident-token-diagram
let ret = value.match(/var\(--[-\w\u{0080}-\u{FFFF}]+(?=[,)])/gui)?.map(p => p.slice(4));
if (ret) {
// Drop duplicates
return [...new Set(ret)];
}
}
let visited = new Set();
let modifiedRules = [];
// Recursively walk a CSSStyleRule or CSSStyleDeclaration
function walkRule(rule, ret) {
if (!rule || visited.has(rule)) {
return;
}
visited.add(rule);
let style, selector;
if (rule instanceof CSSStyleRule && rule.style) {
style = rule.style;
selector = rule.selectorText;
}
else if (rule instanceof CSSStyleDeclaration) {
style = rule;
selector = "";
}
if (style) {
let condition;
// mirror properties to add. We add them afterwards, so we don't pointlessly traverse them
let additions = {};
for (let property of style) {
let value = style.getPropertyValue(property);
if (value.startsWith("url(\"data:image/svg+xml") && value.length > 54) {
value = value.slice(0, 50) + '…' + "\");";
}
let containsRef = value.indexOf("var(--") > -1;
let setsVar = property.indexOf("--") === 0 && property.indexOf("--" + PREFIX) === -1;
if (containsRef || setsVar) {
if (!condition && rule.parentRule) {
condition = [];
let r = rule;
while (r.parentRule?.conditionText) {
r = r.parentRule;
condition.push({
type: r instanceof CSSMediaRule ? "media" : "supports",
test: r.conditionText
});
}
}
if (containsRef) {
// Set mirror property so we can find it in the computed style
additions["--" + PREFIX + property] = value.replace(/var\(--/g, PREFIX + "$&");
let properties = extractValueProperties(value);
for (let prop of properties) {
let info = ret[prop] = ret[prop] || { get: [], set: [] };
info.get.push({ usedIn: property, value, selector, condition });
}
}
if (setsVar) {
let info = ret[property] = ret[property] || { get: [], set: [] };
info.set.push({ value, selector, condition });
}
// Add class so we can find these later
if (selector) {
for (let el of document.querySelectorAll(selector)) {
el.classList.add(`${PREFIX}element`);
}
}
}
}
// Now that we're done, add the mirror properties
for (let property in additions) {
modifiedRules.push({ style, additions });
style.setProperty(property, additions[property]);
}
}
if (rule instanceof CSSMediaRule || rule instanceof CSSSupportsRule) {
// rules with child rules, e.g. @media, @supports
for (let r of rule.cssRules) {
walkRule(r, ret);
}
}
}
// Return a subset of the DOM tree that contains variable reads or writes
function buildGraph() {
// Elements that contain variable reads or writes.
let elements = new Set(document.querySelectorAll(selector));
let map = new Map(); // keep pointers to object for each element
let ret = [];
for (let element of elements) {
map.set(element, { element, children: [] });
}
for (let element of elements) {
let ancestor = element.parentNode.closest?.(selector);
let obj = map.get(element);
if (ancestor) {
let o = map.get(ancestor);
o.children.push(obj)
}
else {
// Top-level
ret.push(obj);
}
let cs = element.computedStyleMap();
let parentCS = element.parentNode.computedStyleMap?.();
let vars = extractVars(cs, parentCS);
if (Object.keys(vars).length > 0) {
obj.declarations = vars;
}
}
return ret;
}
// Extract custom property declarations from a computed style map
// The schema of the returned object is:
// {get: {--var1: [{property, value, computedValue}]}, set: {--var2: {value, type}}}
function extractVars(cs, parentCS) {
let ret = {};
let norefs = {};
for (let [property, [originalValue]] of cs) {
// Do references first
if (property.indexOf("--") === 0) {
let value = originalValue + "";
// Skip inherited values
if (parentCS && (parentCS.get(property) + "" === value + "")) {
continue; // most likely inherited
}
if (property.indexOf("--" + PREFIX) === 0) {
// Usage
let originalProperty = property.replace("--" + PREFIX, "");
value = value.replace(RegExp(PREFIX + "var\\(--", "g"), "var(--");
let properties = extractValueProperties(value);
let computed = cs.get(originalProperty) + "";
ret[originalProperty] = {
value,
references: properties
}
if (computed !== value) {
ret[originalProperty].computed = computed;
}
}
else {
// Definition
norefs[property] = { value };
if (originalValue + "" !== value) {
norefs[property].computed = originalValue + "";
}
// If value is of another type, we have Houdini P&V usage!
if (!(originalValue instanceof CSSUnparsedValue)) {
norefs[property].type = Object.prototype.toString.call(originalValue).slice(8, -1);
}
}
}
}
// Merge static with ret
for (let property in norefs) {
if (!(property in ret)) {
ret[property] = norefs[property];
}
}
return ret;
}
let summary = {};
// Walk through stylesheet and add custom properties for every declaration that uses var()
// This way we can retrieve them in the computed styles and build a dependency graph.
// Otherwise, they get resolved before they hit the computed style.
for (let stylesheet of document.styleSheets) {
try {
var rules = stylesheet.cssRules;
}
catch (e) {
// continue regardless of error
}
if (rules) {
for (let rule of rules) {
walkRule(rule, summary);
}
}
}
function collapseDuplicateSiblings(arr) {
if (arr) {
let map = {};
for (let child of arr) {
let serialized = serialize(child);
if (serialized in map) {
// Dupe
map[serialized]++;
}
else {
map[serialized] = 0;
}
}
let entries = Object.entries(map);
if (entries.length < arr.length) {
// There are duplicates
arr = entries.map(e => {
let child = JSON.parse(e[0]);
if (e[1] > 0) {
child.times = e[1] + 1;
}
return child;
})
}
arr.forEach(o => {
o.children = collapseDuplicateSiblings(o.children);
});
}
return arr;
}
// Do the same thing with inline styles
for (let element of document.querySelectorAll('[style*="--"]')) {
walkRule(element.style, summary);
}
let computed = buildGraph();
// Cleanup: Remove classes
for (let el of document.querySelectorAll(`.${PREFIX}element`)) {
el.classList.remove(`${PREFIX}element`);
}
// Cleanup: Remove custom properties
for (let o of modifiedRules) {
for (let prop in o.additions) {
o.style.removeProperty(prop);
}
}
computed = collapseDuplicateSiblings(computed);
return { summary, computed };
}
function serialize(data, separator) {
return JSON.stringify(data, (key, value) => {
if (value instanceof HTMLElement) {
let str = value.tagName;
if (value.classList.length > 0) {
str += "." + [...value.classList].join(".")
}
if (value.id) {
str += "#" + value.id;
}
return str;
}
// remove empty arrays
if (Array.isArray(value) && value.length === 0) {
return;
}
return value;
}, separator);
}
return serialize(analyzeVariables());