1 | "use strict";
|
2 |
|
3 | var debug = require("debug")("analyze-css:specificity"),
|
4 | specificity = require("specificity"),
|
5 | stats = require("fast-stats").Stats;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | function rule(analyzer) {
|
11 | var types = ["Id", "Class", "Tag"],
|
12 | values = [];
|
13 |
|
14 |
|
15 | types.forEach(function (type) {
|
16 | analyzer.setMetric("specificity" + type + "Avg");
|
17 | analyzer.setMetric("specificity" + type + "Total");
|
18 |
|
19 | values.push(new stats());
|
20 | });
|
21 |
|
22 | analyzer.on("selector", function (rule, selector) {
|
23 | var selectorSpecificity = specificity.calculate(selector),
|
24 | parts;
|
25 |
|
26 |
|
27 | if (!selectorSpecificity || !selectorSpecificity[0]) {
|
28 | debug("not counted for %s!", selector);
|
29 | return;
|
30 | }
|
31 |
|
32 |
|
33 | parts = selectorSpecificity[0].specificity
|
34 | .split(",")
|
35 | .slice(1)
|
36 | .map(function (i) {
|
37 | return parseInt(i, 10);
|
38 | });
|
39 |
|
40 | debug("%s: %s", selector, parts.join(""));
|
41 |
|
42 |
|
43 | parts.forEach(function (val, idx) {
|
44 | values[idx].push(val);
|
45 | });
|
46 | });
|
47 |
|
48 | analyzer.on("report", function () {
|
49 | debug("Gathering stats...");
|
50 |
|
51 | types.forEach(function (type, idx) {
|
52 | analyzer.setMetric(
|
53 | "specificity" + type + "Avg",
|
54 | parseFloat(values[idx].amean().toFixed(2))
|
55 | );
|
56 | analyzer.setMetric("specificity" + type + "Total", values[idx].Σ());
|
57 | });
|
58 |
|
59 | debug("Done");
|
60 | });
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 | rule.description = "Reports rules specificity";
|
66 | module.exports = rule;
|