UNPKG

2.31 kBJavaScriptView Raw
1'use strict';
2
3const atRuleParamIndex = require('../../utils/atRuleParamIndex');
4const declarationValueIndex = require('../../utils/declarationValueIndex');
5const getUnitFromValueNode = require('../../utils/getUnitFromValueNode');
6const optionsMatches = require('../../utils/optionsMatches');
7const report = require('../../utils/report');
8const ruleMessages = require('../../utils/ruleMessages');
9const validateOptions = require('../../utils/validateOptions');
10
11const _ = require('lodash');
12const valueParser = require('postcss-value-parser');
13
14const ruleName = 'number-max-precision';
15
16const messages = ruleMessages(ruleName, {
17 expected: (number, precision) => `Expected "${number}" to be "${number.toFixed(precision)}"`,
18});
19
20function rule(precision, options) {
21 return (root, result) => {
22 const validOptions = validateOptions(
23 result,
24 ruleName,
25 {
26 actual: precision,
27 possible: [_.isNumber],
28 },
29 {
30 optional: true,
31 actual: options,
32 possible: {
33 ignoreUnits: [_.isString, _.isRegExp],
34 },
35 },
36 );
37
38 if (!validOptions) {
39 return;
40 }
41
42 root.walkAtRules((atRule) => {
43 if (atRule.name.toLowerCase() === 'import') {
44 return;
45 }
46
47 check(atRule, atRule.params, atRuleParamIndex);
48 });
49
50 root.walkDecls((decl) => check(decl, decl.value, declarationValueIndex));
51
52 function check(node, value, getIndex) {
53 // Get out quickly if there are no periods
54 if (!value.includes('.')) {
55 return;
56 }
57
58 valueParser(value).walk((valueNode) => {
59 const unit = getUnitFromValueNode(valueNode);
60
61 if (optionsMatches(options, 'ignoreUnits', unit)) {
62 return;
63 }
64
65 // Ignore `url` function
66 if (valueNode.type === 'function' && valueNode.value.toLowerCase() === 'url') {
67 return false;
68 }
69
70 // Ignore strings, comments, etc
71 if (valueNode.type !== 'word') {
72 return;
73 }
74
75 const match = /\d*\.(\d+)/.exec(valueNode.value);
76
77 if (match === null) {
78 return;
79 }
80
81 if (match[1].length <= precision) {
82 return;
83 }
84
85 report({
86 result,
87 ruleName,
88 node,
89 index: getIndex(node) + valueNode.sourceIndex + match.index,
90 message: messages.expected(parseFloat(match[0]), precision),
91 });
92 });
93 }
94 };
95}
96
97rule.ruleName = ruleName;
98rule.messages = messages;
99module.exports = rule;