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 | function rule(analyzer) {
|
19 |
|
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 |
|
38 | if (color === false) {
|
39 | return false;
|
40 | }
|
41 |
|
42 |
|
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 |
|
62 | rule.description = 'Reports number of unique colors used in CSS';
|
63 | module.exports = rule;
|
64 |
|
65 |
|
66 | module.exports.extractColors = extractColors;
|