1 | /**
|
2 | * @fileoverview A rule to ensure consistent quotes used in jsx syntax.
|
3 | * @author Mathias Schreck <https://github.com/lo1tuma>
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | const astUtils = require("../ast-utils");
|
13 |
|
14 | //------------------------------------------------------------------------------
|
15 | // Constants
|
16 | //------------------------------------------------------------------------------
|
17 |
|
18 | const QUOTE_SETTINGS = {
|
19 | "prefer-double": {
|
20 | quote: "\"",
|
21 | description: "singlequote",
|
22 | convert(str) {
|
23 | return str.replace(/'/g, "\"");
|
24 | }
|
25 | },
|
26 | "prefer-single": {
|
27 | quote: "'",
|
28 | description: "doublequote",
|
29 | convert(str) {
|
30 | return str.replace(/"/g, "'");
|
31 | }
|
32 | }
|
33 | };
|
34 |
|
35 | //------------------------------------------------------------------------------
|
36 | // Rule Definition
|
37 | //------------------------------------------------------------------------------
|
38 |
|
39 | module.exports = {
|
40 | meta: {
|
41 | docs: {
|
42 | description: "enforce the consistent use of either double or single quotes in JSX attributes",
|
43 | category: "Stylistic Issues",
|
44 | recommended: false,
|
45 | url: "https://eslint.org/docs/rules/jsx-quotes"
|
46 | },
|
47 |
|
48 | fixable: "whitespace",
|
49 |
|
50 | schema: [
|
51 | {
|
52 | enum: ["prefer-single", "prefer-double"]
|
53 | }
|
54 | ]
|
55 | },
|
56 |
|
57 | create(context) {
|
58 | const quoteOption = context.options[0] || "prefer-double",
|
59 | setting = QUOTE_SETTINGS[quoteOption];
|
60 |
|
61 | /**
|
62 | * Checks if the given string literal node uses the expected quotes
|
63 | * @param {ASTNode} node - A string literal node.
|
64 | * @returns {boolean} Whether or not the string literal used the expected quotes.
|
65 | * @public
|
66 | */
|
67 | function usesExpectedQuotes(node) {
|
68 | return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
|
69 | }
|
70 |
|
71 | return {
|
72 | JSXAttribute(node) {
|
73 | const attributeValue = node.value;
|
74 |
|
75 | if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
|
76 | context.report({
|
77 | node: attributeValue,
|
78 | message: "Unexpected usage of {{description}}.",
|
79 | data: {
|
80 | description: setting.description
|
81 | },
|
82 | fix(fixer) {
|
83 | return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw));
|
84 | }
|
85 | });
|
86 | }
|
87 | }
|
88 | };
|
89 | }
|
90 | };
|