html-quotes.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. // ------------------------------------------------------------------------------
  8. // Requirements
  9. // ------------------------------------------------------------------------------
  10. const utils = require('../utils')
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: 'layout',
  17. docs: {
  18. description: 'enforce quotes style of HTML attributes',
  19. category: 'strongly-recommended',
  20. url: 'https://eslint.vuejs.org/rules/html-quotes.html'
  21. },
  22. fixable: 'code',
  23. schema: [
  24. { enum: ['double', 'single'] }
  25. ]
  26. },
  27. create (context) {
  28. const sourceCode = context.getSourceCode()
  29. const double = context.options[0] !== 'single'
  30. const quoteChar = double ? '"' : "'"
  31. const quoteName = double ? 'double quotes' : 'single quotes'
  32. const quotePattern = double ? /"/g : /'/g
  33. const quoteEscaped = double ? '"' : '''
  34. let hasInvalidEOF
  35. return utils.defineTemplateBodyVisitor(context, {
  36. 'VAttribute[value!=null]' (node) {
  37. if (hasInvalidEOF) {
  38. return
  39. }
  40. const text = sourceCode.getText(node.value)
  41. const firstChar = text[0]
  42. if (firstChar !== quoteChar) {
  43. context.report({
  44. node: node.value,
  45. loc: node.value.loc,
  46. message: 'Expected to be enclosed by {{kind}}.',
  47. data: { kind: quoteName },
  48. fix (fixer) {
  49. const contentText = (firstChar === "'" || firstChar === '"') ? text.slice(1, -1) : text
  50. const replacement = quoteChar + contentText.replace(quotePattern, quoteEscaped) + quoteChar
  51. return fixer.replaceText(node.value, replacement)
  52. }
  53. })
  54. }
  55. }
  56. }, {
  57. Program (node) {
  58. hasInvalidEOF = utils.hasInvalidEOF(node)
  59. }
  60. })
  61. }
  62. }