forked from Intellicode/eslint-plugin-react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort-styles.js
94 lines (77 loc) · 2.51 KB
/
sort-styles.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
87
88
89
90
91
92
93
94
/**
* @fileoverview Rule to require StyleSheet object keys to be sorted
* @author Mats Byrkjeland
*/
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { astHelpers } = require('../util/stylesheet');
const { getStyleDeclarations, isStyleSheetDeclaration } = astHelpers;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = (context) => {
const order = context.options[0] || 'asc';
const options = context.options[1] || {};
const ignoreClassNames = options.ignoreClassNames;
const ignoreStyleProperties = options.ignoreStyleProperties;
const isValidOrder = order === 'asc' ? (a, b) => a <= b : (a, b) => a >= b;
function report(type, node, prev, current) {
const currentName = current.key.name;
const prevName = prev.key.name;
context.report({
node,
message: `Expected ${type} to be in ${order}ending order. '${currentName}' should be before '${prevName}'.`,
loc: current.key.loc,
});
}
function checkIsSorted(array, arrayName, node) {
for (let i = 1; i < array.length; i += 1) {
const previous = array[i - 1];
const current = array[i];
if (previous.type !== 'Property' || current.type !== 'Property') {
return;
}
if (!isValidOrder(previous.key.name, current.key.name)) {
return report(arrayName, node, previous, current);
}
}
}
return {
VariableDeclarator: function (node) {
if (!isStyleSheetDeclaration(node, context.settings)) {
return;
}
const classDefinitions = getStyleDeclarations(node);
if (!ignoreClassNames) {
checkIsSorted(classDefinitions, 'class names', node);
}
if (ignoreStyleProperties) return;
classDefinitions.forEach((classDefinition) => {
const styleProperties = classDefinition.value.properties;
if (!styleProperties || styleProperties.length < 2) {
return;
}
checkIsSorted(styleProperties, 'style properties', node);
});
},
};
};
module.exports.schema = [
{
enum: ['asc', 'desc'],
},
{
type: 'object',
properties: {
ignoreClassNames: {
type: 'boolean',
},
ignoreStyleProperties: {
type: 'boolean',
},
},
additionalProperties: false,
},
];