UNPKG

2.8 kBJavaScriptView Raw
1/**
2 * @fileoverview A rule to ensure consistent quotes used in jsx syntax.
3 * @author Mathias Schreck <https://github.com/lo1tuma>
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Constants
16//------------------------------------------------------------------------------
17
18const 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
39module.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 },
46
47 fixable: "whitespace",
48
49 schema: [
50 {
51 enum: [ "prefer-single", "prefer-double" ]
52 }
53 ]
54 },
55
56 create(context) {
57 const quoteOption = context.options[0] || "prefer-double",
58 setting = QUOTE_SETTINGS[quoteOption];
59
60 /**
61 * Checks if the given string literal node uses the expected quotes
62 * @param {ASTNode} node - A string literal node.
63 * @returns {boolean} Whether or not the string literal used the expected quotes.
64 * @public
65 */
66 function usesExpectedQuotes(node) {
67 return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
68 }
69
70 return {
71 JSXAttribute(node) {
72 const attributeValue = node.value;
73
74 if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
75 context.report({
76 node: attributeValue,
77 message: "Unexpected usage of {{description}}.",
78 data: {
79 description: setting.description
80 },
81 fix(fixer) {
82 return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw));
83 }
84 });
85 }
86 }
87 };
88 }
89};