@ec0lint/plugin-css
Version:
ec0lint plugin that provides rules to verify CSS definition objects
123 lines (122 loc) • 5.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("../utils");
exports.default = (0, utils_1.createRule)("number-leading-zero", {
meta: {
docs: {
description: "require or disallow a leading zero for fractional numbers less than 1",
category: "Stylistic Issues",
recommended: false,
standard: true,
stylelint: "number-leading-zero",
},
fixable: "code",
schema: [
{
enum: ["always", "never"],
},
],
messages: {
expected: "Expected a leading zero.",
unexpected: "Unexpected leading zero.",
},
type: "layout",
},
create(context) {
const option = context.options[0] || "always";
function createVisitor(cssContext) {
const sourceCode = context.getSourceCode();
return {
onProperty(property) {
const value = property.getValue();
if (!value) {
return;
}
if (typeof value.value === "number" ||
!value.value.includes(".")) {
return;
}
value.parsed.walk((node) => {
if (node.type === "function" &&
node.value.toLowerCase() === "url") {
return false;
}
if (node.type !== "word") {
return undefined;
}
if (option === "always") {
const match = /(?:\D|^)(?<decimal>\.\d+)/u.exec(node.value);
if (match == null) {
return undefined;
}
const startIndex = value.expression.range[0] +
node.sourceIndex +
match.index +
match[0].length -
match.groups.decimal.length +
1;
const endIndex = startIndex + match.groups.decimal.length;
const loc = value.directExpression
? {
start: sourceCode.getLocFromIndex(startIndex),
end: sourceCode.getLocFromIndex(endIndex),
}
: undefined;
context.report({
node: value.expression,
loc,
messageId: "expected",
fix(fixer) {
if (cssContext.isFixable(value.directExpression) &&
sourceCode.text[startIndex] === ".") {
return fixer.insertTextBeforeRange([startIndex, endIndex], "0");
}
return null;
},
});
}
else if (option === "never") {
const match = /(?:\D|^)(?<zero>0+)(?<decimal>\.\d+)/u.exec(node.value);
if (match === null) {
return undefined;
}
const startIndex = value.expression.range[0] +
node.sourceIndex +
match.index +
match[0].length -
(match.groups.zero.length +
match.groups.decimal.length) +
1;
const endIndex = startIndex + match.groups.zero.length;
const loc = value.directExpression
? {
start: sourceCode.getLocFromIndex(startIndex),
end: sourceCode.getLocFromIndex(endIndex),
}
: undefined;
context.report({
node: value.expression,
loc,
messageId: "unexpected",
fix(fixer) {
if (cssContext.isFixable(value.directExpression) &&
/^0+$/u.test(sourceCode.text.slice(startIndex, endIndex))) {
return fixer.removeRange([
startIndex,
endIndex,
]);
}
return null;
},
});
}
return undefined;
});
},
};
}
return (0, utils_1.defineCSSVisitor)(context, {
createVisitor,
});
},
});