UNPKG

1.69 kBJavaScriptView Raw
1"use strict";
2
3var debug = require("debug")("analyze-css:specificity"),
4 specificity = require("specificity"),
5 stats = require("fast-stats").Stats;
6
7/**
8 * @param { import("../lib/css-analyzer") } analyzer
9 */
10function rule(analyzer) {
11 var types = ["Id", "Class", "Tag"],
12 values = [];
13
14 // prepare metrics and stacks for values
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 /* istanbul ignore if */
27 if (!selectorSpecificity || !selectorSpecificity[0]) {
28 debug("not counted for %s!", selector);
29 return;
30 }
31
32 // parse the results
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 // add each piece to a separate stack
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// @see http://www.w3.org/TR/css3-selectors/#specificity
64// @see http://css-tricks.com/specifics-on-css-specificity/
65rule.description = "Reports rules specificity";
66module.exports = rule;