-
Notifications
You must be signed in to change notification settings - Fork 0
/
css.js
86 lines (73 loc) · 2.58 KB
/
css.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var parseCSS = require('css-parse');
var internals = {};
internals.formatCssStyle = function (v) {
return ' ' + v.property + ': ' + v.value + '; \n';
};
internals.getCode = function (rule) {
return rule.selectors.join(', ') +
' {\n' + rule.declarations.map(internals.formatCssStyle).join('') + '}\n';
};
// only margin and padding is allowed
internals.declartionVialoation = function (declarations) {
return declarations.some(function (value) {
if (value.type === 'declaration') {
// usages of other than margin and padding
if (!(value.property.indexOf('margin') === 0 || value.property.indexOf('padding') === 0)) {
return true;
}
}
});
};
var RE_VALID_FIRST_SELECTOR = /^[#|\.]{1}/;
internals.hasSelectorViolation = function (rule) {
return !!(
rule && rule.selectors && rule.selectors.length > 0
&& !rule.selectors[0].match(RE_VALID_FIRST_SELECTOR) &&
internals.declartionVialoation(rule.declarations)
);
};
internals.reportErrorOnStyleContent = function (config, report) {
return function (styleContent) {
var parsed;
try {
parsed = parseCSS(styleContent);
} catch (e) {
return report.info('CSS/Styling might be malformed: ' + e.message);
}
if (!parsed || !parsed.stylesheet || !parsed.stylesheet.rules) {
return;
}
parsed.stylesheet.rules.forEach(function (rule) {
if (internals.hasSelectorViolation(rule) === false) {
return;
}
var method = config.strictRules ? 'error' : 'warn';
console.log('internals.hasSelectorViolation(rule)', internals.hasSelectorViolation(rule));
console.log(rule);
report[method]('Styling from style-tag without class or ID prefix found: \"' +
rule.selectors.join(', ') + '\"', {
'code': internals.getCode(rule)
});
});
};
};
internals.validateRules = function (harvested, report, next) {
if (Array.isArray(harvested.css.styles)) {
harvested.css.styles.forEach(
internals.reportErrorOnStyleContent(this, report)
);
} else {
report.debug('Found no styling/styles to inspect');
}
next();
};
module.exports = {
dependencies: ['css'],
validate: function (harvested, report, next) {
if (harvested && harvested.css) {
internals.validateRules.apply(this, Array.prototype.slice.call(arguments));
} else {
next();
}
}
};