|
| 1 | +import * as JSX from "@eslint-react/jsx"; |
| 2 | +import { decodeSettings, normalizeSettings } from "@eslint-react/shared"; |
| 3 | +import { compare } from "compare-versions"; |
| 4 | +import type { CamelCase } from "string-ts"; |
| 5 | + |
| 6 | +import { createRule } from "../utils"; |
| 7 | + |
| 8 | +export const RULE_NAME = "no-context-provider"; |
| 9 | + |
| 10 | +export type MessageID = CamelCase<typeof RULE_NAME>; |
| 11 | + |
| 12 | +export default createRule<[], MessageID>({ |
| 13 | + meta: { |
| 14 | + type: "problem", |
| 15 | + docs: { |
| 16 | + description: "disallow the use of '<Context.Provider>'", |
| 17 | + }, |
| 18 | + fixable: "code", |
| 19 | + messages: { |
| 20 | + noContextProvider: "In React 19, you can render '<Context>' as a provider instead of '<Context.Provider>'.", |
| 21 | + }, |
| 22 | + schema: [], |
| 23 | + }, |
| 24 | + name: RULE_NAME, |
| 25 | + create(context) { |
| 26 | + if (!context.sourceCode.text.includes(".Provider")) return {}; |
| 27 | + const { version } = normalizeSettings(decodeSettings(context.settings)); |
| 28 | + if (compare(version, "19.0.0", "<")) return {}; |
| 29 | + return { |
| 30 | + JSXElement(node) { |
| 31 | + const elementName = JSX.getElementName(node.openingElement); |
| 32 | + if (!elementName.endsWith(".Provider")) return; |
| 33 | + context.report({ |
| 34 | + messageId: "noContextProvider", |
| 35 | + node, |
| 36 | + fix(fixer) { |
| 37 | + const providerName = elementName.replace(/\.Provider$/, ""); |
| 38 | + const openingElement = node.openingElement; |
| 39 | + const closingElement = node.closingElement; |
| 40 | + if (!closingElement) return fixer.replaceText(openingElement.name, providerName); |
| 41 | + return [ |
| 42 | + fixer.replaceText(openingElement.name, providerName), |
| 43 | + fixer.replaceText(closingElement.name, providerName), |
| 44 | + ]; |
| 45 | + }, |
| 46 | + }); |
| 47 | + }, |
| 48 | + }; |
| 49 | + }, |
| 50 | + defaultOptions: [], |
| 51 | +}); |
0 commit comments