UNPKG

eslint-plugin-lit

Version:
96 lines (95 loc) 2.95 kB
/** * @fileoverview Disallows assignments to members of `this` in render methods * @author James Garbutt <https://github.com/43081j> */ import { isLitClass } from '../util.js'; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ export const rule = { meta: { docs: { description: 'Disallows assignments to members of `this` in render methods', recommended: false, url: 'https://github.com/43081j/eslint-plugin-lit/blob/master/docs/rules/no-this-assign-in-render.md' }, schema: [], messages: { noThis: 'Members of `this` should not be assigned to in the render ' + 'method. It is likely you should do this elsewhere instead ' + '(e.g. in `updated`)' } }, create(context) { let inRender = false; let inComponent = false; /** * Class entered * * @param {ESTree.Class} node Node entered * @return {void} */ function classEnter(node) { if (!isLitClass(node, context)) { return; } inComponent = true; } /** * Class exited * * @return {void} */ function classExit() { inComponent = false; } /** * Method entered * * @param {ESTree.MethodDefinition} node Node entered * @return {void} */ function methodEnter(node) { if (!inComponent || node.kind !== 'method' || node.static === true || node.key.type !== 'Identifier' || node.key.name !== 'render') { return; } inRender = true; } /** * Method exited * * @return {void} */ function methodExit() { inRender = false; } /** * Left side of an assignment expr found * * @param {Rule.Node} node Node entered * @return {void} */ function assignmentFound(node) { if (!inRender || !node.parent) { return; } context.report({ node: node.parent, messageId: 'noThis' }); } return { ClassExpression: (node) => classEnter(node), ClassDeclaration: (node) => classEnter(node), 'ClassExpression:exit': classExit, 'ClassDeclaration:exit': classExit, MethodDefinition: (node) => methodEnter(node), 'MethodDefinition:exit': methodExit, 'AssignmentExpression > .left:has(ThisExpression)': (node) => assignmentFound(node) }; } };