UNPKG

2.05 kBJavaScriptView Raw
1"use strict";
2
3var format = require("util").format,
4 shorthandProperties = require("css-shorthand-properties");
5
6/**
7 * Detect accidental property resets
8 *
9 * @see http://css-tricks.com/accidental-css-resets/
10 * @param { import("../lib/css-analyzer") } analyzer
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"
25 ? declaration.property
26 : false;
27 })
28 .filter(function (item) {
29 return item !== false;
30 });
31
32 debug("%s: %j", selector, properties);
33
34 // iterate through all properties, expand shorthand properties and
35 // check if there's no expanded version of it earlier in the array
36 properties.forEach(function (property, idx) {
37 var expanded;
38
39 // skip if the current property is not the shorthand version
40 if (
41 typeof shorthandProperties.shorthandProperties[property] === "undefined"
42 ) {
43 return;
44 }
45
46 // property = 'margin'
47 // expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
48 expanded = shorthandProperties.expand(property);
49 debug("%s: %s", property, expanded.join(", "));
50
51 expanded.forEach(function (expandedProperty) {
52 var propertyPos = properties.indexOf(expandedProperty);
53
54 if (propertyPos > -1 && propertyPos < idx) {
55 analyzer.incrMetric("propertyResets");
56 analyzer.addOffender(
57 "propertyResets",
58 format(
59 '%s: "%s" resets "%s" property set earlier',
60 selector,
61 property,
62 expandedProperty
63 )
64 );
65 }
66 });
67 });
68 });
69}
70
71rule.description = "Reports accidental property resets";
72module.exports = rule;