UNPKG

1.68 kBJavaScriptView Raw
1"use strict";
2
3/**
4 * @param { import("../lib/css-analyzer") } analyzer
5 */
6function rule(analyzer) {
7 let selectors = 0,
8 selectorsLength = 0;
9
10 analyzer.setMetric("selectors");
11 analyzer.setMetric("selectorLengthAvg");
12
13 analyzer.setMetric("selectorsByAttribute");
14 analyzer.setMetric("selectorsByClass");
15 analyzer.setMetric("selectorsById");
16 analyzer.setMetric("selectorsByPseudo");
17 analyzer.setMetric("selectorsByTag");
18
19 analyzer.on("rule", () => {
20 analyzer.incrMetric("rules");
21 });
22
23 analyzer.on("selector", (_, __, expressions) => {
24 selectors += 1;
25 selectorsLength +=
26 expressions.filter((item) => {
27 return ["child", "descendant"].includes(item.type);
28 }).length + 1;
29 });
30
31 analyzer.on("declaration", () => {
32 analyzer.incrMetric("declarations");
33 });
34
35 analyzer.on("expression", (selector, expression) => {
36 // console.log(selector, expression);
37
38 // a[href]
39 if (["exists"].includes(expression.action)) {
40 analyzer.incrMetric("selectorsByAttribute");
41 }
42
43 // .bar
44 if (expression.name === "class") {
45 analyzer.incrMetric("selectorsByClass");
46 }
47
48 // #foo
49 if (expression.name === "id") {
50 analyzer.incrMetric("selectorsById");
51 }
52
53 // a:hover
54 if (expression.type === "pseudo") {
55 analyzer.incrMetric("selectorsByPseudo");
56 }
57
58 // header
59 if (expression.type === "tag") {
60 analyzer.incrMetric("selectorsByTag");
61 }
62 });
63
64 analyzer.on("report", () => {
65 analyzer.setMetric("selectors", selectors);
66 analyzer.setMetric("selectorLengthAvg", selectorsLength / selectors);
67 });
68}
69
70rule.description = "Emit CSS stats";
71module.exports = rule;