|
| 1 | +import * as AST from "@eslint-react/ast"; |
| 2 | +import type { RuleContext, RuleFeature } from "@eslint-react/shared"; |
| 3 | +import type { TSESTree } from "@typescript-eslint/types"; |
| 4 | +import { AST_NODE_TYPES as T } from "@typescript-eslint/types"; |
| 5 | +import type { RuleListener } from "@typescript-eslint/utils/ts-eslint"; |
| 6 | +import type { CamelCase } from "string-ts"; |
| 7 | + |
| 8 | +import { createRule } from "../utils"; |
| 9 | + |
| 10 | +export const RULE_NAME = "jsx-dollar"; |
| 11 | + |
| 12 | +export const RULE_FEATURES = [] as const satisfies RuleFeature[]; |
| 13 | + |
| 14 | +export type MessageID = CamelCase<typeof RULE_NAME> | "removeDollarSign"; |
| 15 | + |
| 16 | +export default createRule<[], MessageID>({ |
| 17 | + meta: { |
| 18 | + type: "problem", |
| 19 | + docs: { |
| 20 | + description: "Prevents dollar signs from being inserted as text nodes before expressions.", |
| 21 | + [Symbol.for("rule_features")]: RULE_FEATURES, |
| 22 | + }, |
| 23 | + fixable: "code", |
| 24 | + hasSuggestions: true, |
| 25 | + messages: { |
| 26 | + jsxDollar: |
| 27 | + "Possible misused dollar sign in text node. If you want to explicitly display '$' character i.e. show price, you can use template literals.", |
| 28 | + removeDollarSign: "Remove the dollar sign '$' before the expression.", |
| 29 | + }, |
| 30 | + schema: [], |
| 31 | + }, |
| 32 | + name: RULE_NAME, |
| 33 | + create, |
| 34 | + defaultOptions: [], |
| 35 | +}); |
| 36 | + |
| 37 | +export function create(context: RuleContext<MessageID, []>): RuleListener { |
| 38 | + const visitorFunction = (node: TSESTree.JSXElement | TSESTree.JSXFragment) => { |
| 39 | + for (const [index, child] of node.children.entries()) { |
| 40 | + if (child.type !== T.JSXText) continue; |
| 41 | + if (!child.raw.endsWith("$")) continue; |
| 42 | + if (node.children[index + 1]?.type !== T.JSXExpressionContainer) continue; |
| 43 | + context.report({ |
| 44 | + messageId: "jsxDollar", |
| 45 | + node: child, |
| 46 | + suggest: [ |
| 47 | + { |
| 48 | + messageId: "removeDollarSign", |
| 49 | + fix(fixer) { |
| 50 | + return fixer.removeRange([child.range[1] - 1, child.range[1]]); |
| 51 | + }, |
| 52 | + }, |
| 53 | + ], |
| 54 | + }); |
| 55 | + } |
| 56 | + }; |
| 57 | + return { |
| 58 | + JSXElement: visitorFunction, |
| 59 | + JSXFragment: visitorFunction, |
| 60 | + }; |
| 61 | +} |
0 commit comments