UNPKG

1.81 kBJavaScriptView Raw
1'use strict';
2
3var debug = require('debug')('analyze-css:propertyResets'),
4 format = require('util').format,
5 shorthandProperties = require('css-shorthand-properties');
6
7/**
8 * Detect accidental property resets
9 *
10 * @see http://css-tricks.com/accidental-css-resets/
11 */
12function rule(analyzer) {
13 var debug = require('debug');
14
15 analyzer.setMetric('propertyResets');
16
17 analyzer.on('selector', function(rule, selector) {
18 var declarations = rule.declarations || [],
19 properties;
20
21 // prepare the list of properties used in this selector
22 properties = declarations.
23 map(function(declaration) {
24 return (declaration.type === 'declaration') ? declaration.property : false;
25 }).
26 filter(function(item) {
27 return item !== false;
28 });
29
30 debug('%s: %j', selector, properties);
31
32 // iterate through all properties, expand shorthand properties and
33 // check if there's no expanded version of it earlier in the array
34 properties.forEach(function(property, idx) {
35 var expanded;
36
37 // skip if the current property is not the shorthand version
38 if (typeof shorthandProperties.shorthandProperties[property] === 'undefined') {
39 return;
40 }
41
42 // property = 'margin'
43 // expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
44 expanded = shorthandProperties.expand(property);
45 debug('%s: %s', property, expanded.join(', '));
46
47 expanded.forEach(function(expandedProperty) {
48 var propertyPos = properties.indexOf(expandedProperty);
49
50 if (propertyPos > -1 && propertyPos < idx) {
51 analyzer.incrMetric('propertyResets');
52 analyzer.addOffender('propertyResets', format('%s: "%s" resets "%s" property set earlier', selector, property, expandedProperty));
53 }
54 });
55 });
56 });
57}
58
59rule.description = 'Reports accidental property resets';
60module.exports = rule;