3 const atRuleParamIndex = require("../../utils/atRuleParamIndex");
4 const declarationValueIndex = require("../../utils/declarationValueIndex");
5 const report = require("../../utils/report");
6 const ruleMessages = require("../../utils/ruleMessages");
7 const validateOptions = require("../../utils/validateOptions");
8 const valueParser = require("postcss-value-parser");
10 const ruleName = "number-no-trailing-zeros";
12 const messages = ruleMessages(ruleName, {
13 rejected: "Unexpected trailing zero(s)"
16 const rule = function(actual, secondary, context) {
17 return (root, result) => {
18 const validOptions = validateOptions(result, ruleName, { actual });
23 root.walkAtRules(atRule => {
24 if (atRule.name.toLowerCase() === "import") {
28 check(atRule, atRule.params, atRuleParamIndex);
31 root.walkDecls(decl => check(decl, decl.value, declarationValueIndex));
33 function check(node, value, getIndex) {
34 const fixPositions = [];
36 // Get out quickly if there are no periods
37 if (value.indexOf(".") === -1) {
41 valueParser(value).walk(valueNode => {
42 // Ignore `url` function
44 valueNode.type === "function" &&
45 valueNode.value.toLowerCase() === "url"
50 // Ignore strings, comments, etc
51 if (valueNode.type !== "word") {
55 const match = /\.(\d*?)(0+)(?:\D|$)/.exec(valueNode.value);
56 // match[1] is any numbers between the decimal and our trailing zero, could be empty
57 // match[2] is our trailing zero(s)
63 // the index of our valueNode +
64 // the index of our match +
65 // 1 for our decimal +
66 // the length of our potential non-zero number match (match[1])
67 const index = valueNode.sourceIndex + match.index + 1 + match[1].length;
69 // our startIndex is identical to our index except when we have only
70 // trailing zeros after our decimal. in that case we don't need the decimal
71 // either so we move our index back by 1.
72 const startIndex = match[1].length > 0 ? index : index - 1;
74 // our end index is our original index + the length of our trailing zeros
75 const endIndex = index + match[2].length;
78 fixPositions.unshift({
85 message: messages.rejected,
87 // this is the index of the _first_ trailing zero
88 index: getIndex(node) + index,
95 if (fixPositions.length) {
96 fixPositions.forEach(function(fixPosition) {
97 const startIndex = fixPosition.startIndex;
98 const endIndex = fixPosition.endIndex;
99 if (node.type === "atrule") {
100 node.params = removeTrailingZeros(
106 node.value = removeTrailingZeros(node.value, startIndex, endIndex);
114 function removeTrailingZeros(input, startIndex, endIndex) {
115 return input.slice(0, startIndex) + input.slice(endIndex);
118 rule.ruleName = ruleName;
119 rule.messages = messages;
120 module.exports = rule;