-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
92 lines (83 loc) · 2.44 KB
/
index.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
const { isArray, isString } = require("lodash");
const { parse } = require("postcss-values-parser");
const {
createPlugin,
utils: { report, ruleMessages, validateOptions }
} = require("stylelint");
const {
absoluteLengths,
fontRelativeLengths
} = require("../../reference/valueSets");
const parseShorthandBorder = require("../../utils/parseShorthandBorder");
const lengthUnits = [...absoluteLengths, ...fontRelativeLengths];
const ruleName = "scales/border-width";
const messages = ruleMessages(ruleName, {
expected: (value, scale) => `Expected "${value}" to be one of "${scale}"`
});
const rule = (scale, options = {}) => {
return (root, result) => {
// Validate the options
const validOptions = validateOptions(
result,
ruleName,
{
actual: scale,
possible: isArray
},
{
actual: options,
possible: {
unit: isString
},
optional: true
}
);
if (!validOptions) return;
const { unit } = options;
// Check border-width
root.walkDecls("border-width", decl => {
const { value } = decl;
check(decl, value);
});
// Check border-width
root.walkDecls("border", decl => {
const { value } = decl;
if (value === "none") return;
const { borderWidth } = parseShorthandBorder(value, result, decl);
check(decl, borderWidth);
});
// Check the size
function check(decl, size) {
// Parse the size and walk through Numerics
parse(size, {
ignoreUnknownWords: true
}).walkNumerics(({ value, unit: valueUnit }) => {
// Return early if not a checked unit
if (!lengthUnits.includes(valueUnit)) return;
// Validate scale and units
const validUnit = unit ? valueUnit === unit : true;
const validScale = scale.includes(Math.abs(Number(value)));
// Get message of the violation
let message;
if (!validScale) {
message = messages.expected(`${value}`, scale.join(", "));
} else if (!validUnit) {
message = messages.expected(`${valueUnit}`, `${unit}`);
} else {
return;
}
// Report the violation to stylelint
report({
message,
node: decl,
result,
ruleName,
word: value
});
});
}
};
};
module.exports = createPlugin(ruleName, rule);
module.exports.ruleName = ruleName;
module.exports.messages = messages;