|
| 1 | +const {availableCasings, casingMatches} = require('../utils/casing-matches') |
| 2 | +const {identifierIsCSSModuleBinding} = require('../utils/css-modules') |
| 3 | + |
| 4 | +module.exports = { |
| 5 | + meta: { |
| 6 | + type: 'suggestion', |
| 7 | + fixable: 'code', |
| 8 | + schema: [ |
| 9 | + { |
| 10 | + properties: { |
| 11 | + casing: { |
| 12 | + enum: availableCasings, |
| 13 | + }, |
| 14 | + }, |
| 15 | + }, |
| 16 | + ], |
| 17 | + messages: { |
| 18 | + bad: 'Class names should be in a recognisable case, and either an identifier or literal, saw: {{ type }}', |
| 19 | + camel: 'Class names should be camelCase in both CSS and JS, saw: {{ name }}', |
| 20 | + pascal: 'Class names should be PascalCase in both CSS and JS, saw: {{ name }}', |
| 21 | + kebab: 'Class names should be kebab-case in both CSS and JS, saw: {{ name }}', |
| 22 | + }, |
| 23 | + }, |
| 24 | + create(context) { |
| 25 | + const casing = context.options[0]?.casing || 'pascal' |
| 26 | + return { |
| 27 | + ['JSXAttribute[name.name="className"] JSXExpressionContainer MemberExpression[object.type="Identifier"]']: |
| 28 | + function (node) { |
| 29 | + if (!identifierIsCSSModuleBinding(node.object, context)) return |
| 30 | + if (!node.computed && node.property?.type === 'Identifier') { |
| 31 | + if (!casingMatches(node.property.name || '', casing)) { |
| 32 | + context.report({ |
| 33 | + node: node.property, |
| 34 | + messageId: casing, |
| 35 | + data: {name: node.property.name}, |
| 36 | + }) |
| 37 | + } |
| 38 | + } else if (node.property?.type === 'Literal') { |
| 39 | + if (!casingMatches(node.property.value || '', casing)) { |
| 40 | + context.report({ |
| 41 | + node: node.property, |
| 42 | + messageId: casing, |
| 43 | + data: {name: node.property.value}, |
| 44 | + }) |
| 45 | + } |
| 46 | + } else if (node.computed) { |
| 47 | + const ref = context |
| 48 | + .getScope() |
| 49 | + .references.find(reference => reference.identifier.name === node.property.name) |
| 50 | + const def = ref.resolved?.defs?.[0] |
| 51 | + if (def?.node?.init?.type === 'Literal') { |
| 52 | + if (!casingMatches(def.node.init.value || '', casing)) { |
| 53 | + context.report({ |
| 54 | + node: node.property, |
| 55 | + messageId: casing, |
| 56 | + data: {name: def.node.init.value}, |
| 57 | + }) |
| 58 | + } |
| 59 | + } else { |
| 60 | + context.report({ |
| 61 | + node: node.property, |
| 62 | + messageId: 'bad', |
| 63 | + data: {type: node.property.type}, |
| 64 | + }) |
| 65 | + } |
| 66 | + } else { |
| 67 | + context.report({ |
| 68 | + node: node.property, |
| 69 | + messageId: 'bad', |
| 70 | + data: {type: node.property.type}, |
| 71 | + }) |
| 72 | + } |
| 73 | + }, |
| 74 | + } |
| 75 | + }, |
| 76 | +} |
0 commit comments