forked from DealerDotCom/css-compare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
css-compare.js
61 lines (52 loc) · 1.69 KB
/
css-compare.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
// Using Rework, not PostCSS, because Rework does reformat whitespace.
var rework = require('rework');
var fs = require('fs');
var color = require('color-parser');
var diff = require('diff');
function colorString(value) {
var c = color(value);
if (c) {
c = 'rgba('+c.r+', '+c.g+', '+c.b+', '+(c.a||1)+');';
}
return c;
}
function normalize(root, rw) {
// TODO: Use the source position to inform our diff?
root.rules = root.rules.filter(function(rule){
return rule.type !== 'comment';
});
root.rules.forEach(function(rule){
if (rule.selectors) {
rule.selectors = rule.selectors.map(function(selector){
return selector
.replace(/\s+/g, ' ')
.replace(/\s*([+>])\s*/g, ' $1 ');
});
}
if (rule.declarations) {
rule.declarations.forEach(function(declaration){
if (declaration.value) {
declaration.value = colorString(declaration.value) || declaration.value;
declaration.value = declaration.value
.replace(/,\s*/g, ', ')
.replace(/'/g, '"');
}
});
}
});
}
module.exports = function(test, control, label, output){
var controlOutput = rework(fs.readFileSync(control).toString()).use(normalize).toString();
var testOutput = rework(fs.readFileSync(test).toString()).use(normalize).toString();
if (output) {
var controlPath = control.replace('.css', '-normalized.css');
var testPath = test.replace('.css', '-normalized.css');
fs.writeFileSync(controlPath, controlOutput);
fs.writeFileSync(testPath, testOutput);
}
return {
"diff": diff.createPatch(label || test, controlOutput, testOutput),
"control": controlOutput,
"test": testOutput
}
}