UNPKG

1.51 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
18function rule(analyzer) {
19 // store unique colors with the counter
20 var colors = new collection();
21
22 analyzer.setMetric('colors');
23
24 analyzer.on('declaration', function(rule, property, value) {
25 var extractedColors = extractColors(value);
26
27 if (extractedColors === false) {
28 return;
29 }
30
31 debug('%s: %s -> %j', property, value, extractedColors);
32
33 extractedColors.
34 map(function(item) {
35 var color = onecolor(item);
36
37 // handle parsing errors
38 if (color === false) {
39 return false;
40 }
41
42 // return either rgba(0,0,0,0.25) or #000000
43 return (color.alpha() < 1.0) ? color.cssa() : color.hex();
44 }).
45 forEach(function(color) {
46 if (color !== false) {
47 colors.push(color);
48 }
49 });
50 });
51
52 analyzer.on('report', function() {
53 analyzer.setCurrentPosition(undefined);
54
55 colors.sort().forEach(function(color, cnt) {
56 analyzer.incrMetric('colors');
57 analyzer.addOffender('colors', format('%s (%d times)', color, cnt));
58 });
59 });
60}
61
62rule.description = 'Reports number of unique colors used in CSS';
63module.exports = rule;
64
65// expose for unit testing
66module.exports.extractColors = extractColors;