1 | "use strict";
|
2 |
|
3 | var collection = require("../lib/collection"),
|
4 | debug = require("debug")("analyze-css:colors"),
|
5 | format = require("util").format,
|
6 | onecolor = require("onecolor");
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | var regex = /(((rgba?|hsl)\([^)]+\))|#(\w{3,6}))/g;
|
12 |
|
13 | function extractColors(value) {
|
14 | var matches = value.match(regex);
|
15 | return matches || false;
|
16 | }
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function rule(analyzer) {
|
22 |
|
23 | var colors = new collection();
|
24 |
|
25 | analyzer.setMetric("colors");
|
26 |
|
27 | analyzer.on("declaration", function (rule, property, value) {
|
28 | var extractedColors = extractColors(value);
|
29 |
|
30 | if (extractedColors === false) {
|
31 | return;
|
32 | }
|
33 |
|
34 | debug("%s: %s -> %j", property, value, extractedColors);
|
35 |
|
36 | extractedColors
|
37 | .map(function (item) {
|
38 | var color = onecolor(item);
|
39 |
|
40 |
|
41 | if (color === false) {
|
42 | return false;
|
43 | }
|
44 |
|
45 |
|
46 | return color.alpha() < 1.0 ? color.cssa() : color.hex();
|
47 | })
|
48 | .forEach(function (color) {
|
49 | if (color !== false) {
|
50 | colors.push(color);
|
51 | }
|
52 | });
|
53 | });
|
54 |
|
55 | analyzer.on("report", function () {
|
56 | analyzer.setCurrentPosition(undefined);
|
57 |
|
58 | colors.sort().forEach(function (color, cnt) {
|
59 | analyzer.incrMetric("colors");
|
60 | analyzer.addOffender("colors", format("%s (%d times)", color, cnt));
|
61 | });
|
62 | });
|
63 | }
|
64 |
|
65 | rule.description = "Reports number of unique colors used in CSS";
|
66 | module.exports = rule;
|
67 |
|
68 |
|
69 | module.exports.extractColors = extractColors;
|