UNPKG

1.68 kBJavaScriptView Raw
1"use strict";
2
3var collection = require("../lib/collection"),
4 debug = require("debug")("analyze-css:colors"),
5 format = require("util").format,
6 onecolor = require("onecolor");
7
8/**
9 * Extract CSS colors from given CSS property value
10 */
11var regex = /(((rgba?|hsl)\([^)]+\))|#(\w{3,6}))/g;
12
13function extractColors(value) {
14 var matches = value.match(regex);
15 return matches || false;
16}
17
18/**
19 * @param { import("../lib/css-analyzer") } analyzer
20 */
21function rule(analyzer) {
22 // store unique colors with the counter
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 // handle parsing errors
41 if (color === false) {
42 return false;
43 }
44
45 // return either rgba(0,0,0,0.25) or #000000
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
65rule.description = "Reports number of unique colors used in CSS";
66module.exports = rule;
67
68// expose for unit testing
69module.exports.extractColors = extractColors;