|
| 1 | +import { isPandaAttribute, isPandaProp, isValidProperty, resolveLonghand } from '../utils/helpers' |
| 2 | +import { type Rule, createRule } from '../utils' |
| 3 | +import { compositeProperties } from '../utils/composite-properties' |
| 4 | +import { isIdentifier, isJSXIdentifier } from '../utils/nodes' |
| 5 | + |
| 6 | +export const RULE_NAME = 'prefer-composite-properties' |
| 7 | + |
| 8 | +const rule: Rule = createRule({ |
| 9 | + name: RULE_NAME, |
| 10 | + meta: { |
| 11 | + docs: { |
| 12 | + description: 'Encourage the use of composite properties instead of atomic properties in the codebase.', |
| 13 | + }, |
| 14 | + messages: { |
| 15 | + composite: 'Use composite property of `{{atomic}}` instead. \nPrefer: {{composite}}', |
| 16 | + }, |
| 17 | + type: 'suggestion', |
| 18 | + schema: [], |
| 19 | + }, |
| 20 | + defaultOptions: [], |
| 21 | + create(context) { |
| 22 | + const resolveCompositeProperty = (name: string) => { |
| 23 | + const longhand = resolveLonghand(name, context) ?? name |
| 24 | + |
| 25 | + if (!isValidProperty(longhand, context)) return |
| 26 | + return Object.keys(compositeProperties).find((cpd) => compositeProperties[cpd].includes(longhand)) |
| 27 | + } |
| 28 | + |
| 29 | + const sendReport = (node: any, name: string) => { |
| 30 | + const cmp = resolveCompositeProperty(name)! |
| 31 | + |
| 32 | + return context.report({ |
| 33 | + node, |
| 34 | + messageId: 'composite', |
| 35 | + data: { |
| 36 | + composite: cmp, |
| 37 | + atomic: name, |
| 38 | + }, |
| 39 | + }) |
| 40 | + } |
| 41 | + |
| 42 | + return { |
| 43 | + JSXAttribute(node) { |
| 44 | + if (!isJSXIdentifier(node.name)) return |
| 45 | + if (!isPandaProp(node, context)) return |
| 46 | + |
| 47 | + const atm = resolveCompositeProperty(node.name.name) |
| 48 | + if (!atm) return |
| 49 | + |
| 50 | + sendReport(node, node.name.name) |
| 51 | + }, |
| 52 | + |
| 53 | + Property(node) { |
| 54 | + if (!isIdentifier(node.key)) return |
| 55 | + if (!isPandaAttribute(node, context)) return |
| 56 | + const atm = resolveCompositeProperty(node.key.name) |
| 57 | + if (!atm) return |
| 58 | + |
| 59 | + sendReport(node.key, node.key.name) |
| 60 | + }, |
| 61 | + } |
| 62 | + }, |
| 63 | +}) |
| 64 | + |
| 65 | +export default rule |
0 commit comments