|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Checks if a node is a css() call from emotion. |
| 5 | + * @param {Object} node - AST node to check. |
| 6 | + * @returns {boolean} - Whether the node is a css() call. |
| 7 | + */ |
| 8 | +function isCssCall(node) { |
| 9 | + return ( |
| 10 | + node && |
| 11 | + node.type === 'CallExpression' && |
| 12 | + node.callee && |
| 13 | + node.callee.type === 'Identifier' && |
| 14 | + node.callee.name === 'css' |
| 15 | + ); |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Checks if a call is inside a react function. |
| 20 | + * This only checks for JSXExpressionContainers or an uppercase function name, |
| 21 | + * so it may miss some cases. |
| 22 | + * @param {Object} context - ESLint context. |
| 23 | + * @returns {boolean} - Whether we're inside a function. |
| 24 | + */ |
| 25 | +function isInsideReactFunction(context) { |
| 26 | + const ancestors = context.getAncestors(); |
| 27 | + |
| 28 | + const hasJSXAncestor = ancestors.some( |
| 29 | + (ancestor) => ancestor.type === 'JSXExpressionContainer' |
| 30 | + ); |
| 31 | + |
| 32 | + if (hasJSXAncestor) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + const currentFunction = ancestors.find( |
| 37 | + (ancestor) => |
| 38 | + ancestor.type === 'FunctionDeclaration' || |
| 39 | + ancestor.type === 'FunctionExpression' || |
| 40 | + ancestor.type === 'ArrowFunctionExpression' |
| 41 | + ); |
| 42 | + if (currentFunction) { |
| 43 | + // If the function name starts with an uppercase letter maybe it's a React component. |
| 44 | + if ( |
| 45 | + currentFunction.type === 'FunctionDeclaration' && |
| 46 | + currentFunction.id && |
| 47 | + /^[A-Z]/.test(currentFunction.id.name) |
| 48 | + ) { |
| 49 | + return true; |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 55 | +module.exports = { |
| 56 | + meta: { |
| 57 | + type: 'problem', |
| 58 | + docs: { |
| 59 | + description: 'Disallow dynamic emotion css() calls in render methods', |
| 60 | + }, |
| 61 | + messages: { |
| 62 | + noInlineCSS: |
| 63 | + "Don't use a dynamic css() call in the render method, this creates a new class name every time component updates and is not performant. Static styles can be defined with css outside of render, dynamic should be passed through the style prop.", |
| 64 | + }, |
| 65 | + }, |
| 66 | + |
| 67 | + create(context) { |
| 68 | + return { |
| 69 | + // Check for dynamic css() calls in react rendering. |
| 70 | + CallExpression(node) { |
| 71 | + if (!isCssCall(node)) { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + if (isInsideReactFunction(context)) { |
| 76 | + context.report({ |
| 77 | + node, |
| 78 | + messageId: 'noInlineCSS', |
| 79 | + }); |
| 80 | + } |
| 81 | + }, |
| 82 | + }; |
| 83 | + }, |
| 84 | +}; |
0 commit comments