UNPKG

eslint-plugin-hooks-logic-order

Version:

Allows component-code's logical blocks keep in defined order

100 lines 5.19 kB
"use strict"; const rule = { meta: { type: "layout", docs: { description: "Allows component-code's logical blocks keep in defined order. Triggers when component have 'useEffect' expression", }, fixable: undefined, schema: [ { type: "object", properties: { order: { type: "array", maxLength: 5, minLength: 5, items: { enum: ["hook2var", "var", "hook", "func", "others"], }, }, }, additionalProperties: false, }, ], }, create: context => { return { ExpressionStatement: node => { const checkOrder = context.options[0].order; // check for useEffect call expr if (node.expression.type === "CallExpression") { if (node.expression.callee.type === "Identifier") { if (node.expression.callee.name.startsWith("use")) { const parent = node.parent; const statements = parent.body; const statementsFormatted = []; // format AST to something plain and processable statements.forEach(statement => { var _a, _b, _c; if (statement.type === "VariableDeclaration") { const declare = statement.declarations.at(0); if ((declare === null || declare === void 0 ? void 0 : declare.type) === "VariableDeclarator") { if (((_a = declare.init) === null || _a === void 0 ? void 0 : _a.type) === "CallExpression") { if (declare.init.callee.type === "Identifier") { if (declare.init.callee.name.startsWith("use")) { statementsFormatted.push("hook2var"); } else { statementsFormatted.push("var"); } } } else if (((_b = declare.init) === null || _b === void 0 ? void 0 : _b.type) === "ArrowFunctionExpression") { statementsFormatted.push("func"); } else { statementsFormatted.push("var"); } } } else if (statement.type === "FunctionDeclaration") { statementsFormatted.push("func"); } else if (statement.type === "ExpressionStatement") { if (statement.expression.type === "CallExpression") { if (statement.expression.callee.type === "Identifier") { if ((_c = statement.expression.callee.name) === null || _c === void 0 ? void 0 : _c.startsWith("use")) { statementsFormatted.push("hook"); } else { statementsFormatted.push("others"); } } } } else { statementsFormatted.push("others"); } }); // check statements order const sorted = statementsFormatted .map(_ => checkOrder.findIndex(__ => __ === _)) .sort((a, b) => a - b) .map(_ => checkOrder[_]); const ok = sorted.join("-") === statementsFormatted.join("-"); if (!ok) { context.report({ message: `Wrong logic block order in component! Check your .eslintrc rules for correct block order`, node, }); } } } } }, }; }, }; module.exports = rule; //# sourceMappingURL=hooks-on-top.js.map