|
| 1 | +/** |
| 2 | + * @fileoverview Enforce props quotes style |
| 3 | + * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton, Yannick Croissant |
| 4 | + */ |
| 5 | +'use strict'; |
| 6 | + |
| 7 | +// ------------------------------------------------------------------------------ |
| 8 | +// Constants |
| 9 | +// ------------------------------------------------------------------------------ |
| 10 | + |
| 11 | +var QUOTE_SETTINGS = { |
| 12 | + double: { |
| 13 | + quote: '"', |
| 14 | + alternateQuote: '\'', |
| 15 | + description: 'doublequote' |
| 16 | + }, |
| 17 | + single: { |
| 18 | + quote: '\'', |
| 19 | + alternateQuote: '"', |
| 20 | + description: 'singlequote' |
| 21 | + } |
| 22 | +}; |
| 23 | + |
| 24 | +var AVOID_ESCAPE = 'avoid-escape'; |
| 25 | + |
| 26 | +// ------------------------------------------------------------------------------ |
| 27 | +// Rule Definition |
| 28 | +// ------------------------------------------------------------------------------ |
| 29 | + |
| 30 | +module.exports = function(context) { |
| 31 | + |
| 32 | + /** |
| 33 | + * Validate that a string passed in is surrounded by the specified character |
| 34 | + * @param {string} val The text to check. |
| 35 | + * @param {string} character The character to see if it's surrounded by. |
| 36 | + * @returns {boolean} True if the text is surrounded by the character, false if not. |
| 37 | + * @private |
| 38 | + */ |
| 39 | + function isSurroundedBy(val, character) { |
| 40 | + return val[0] === character && val[val.length - 1] === character; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Determines if a given node is part of JSX syntax. |
| 45 | + * @param {ASTNode} node The node to check. |
| 46 | + * @returns {boolean} True if the node is a JSX node, false if not. |
| 47 | + * @private |
| 48 | + */ |
| 49 | + function isJSXElement(node) { |
| 50 | + return node.type.indexOf('JSX') === 0; |
| 51 | + } |
| 52 | + |
| 53 | + return { |
| 54 | + |
| 55 | + Literal: function(node) { |
| 56 | + if (!isJSXElement(node.parent)) { |
| 57 | + return; |
| 58 | + } |
| 59 | + var val = node.value; |
| 60 | + var rawVal = node.raw; |
| 61 | + var quoteOption = context.options[0]; |
| 62 | + var settings = QUOTE_SETTINGS[quoteOption]; |
| 63 | + var avoidEscape = context.options[1] === AVOID_ESCAPE; |
| 64 | + var isValid; |
| 65 | + |
| 66 | + if (settings && typeof val === 'string') { |
| 67 | + isValid = isSurroundedBy(rawVal, settings.quote); |
| 68 | + |
| 69 | + if (!isValid && avoidEscape) { |
| 70 | + isValid = isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0; |
| 71 | + } |
| 72 | + |
| 73 | + if (!isValid) { |
| 74 | + context.report(node, 'JSX attributes must use ' + settings.description + '.'); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + }; |
| 79 | + |
| 80 | +}; |
0 commit comments