html-quotes.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. docs: {
  17. description: 'enforce quotes style of HTML attributes',
  18. category: 'recommended',
  19. url: 'https://github.com/vuejs/eslint-plugin-vue/blob/v4.7.1/docs/rules/html-quotes.md'
  20. },
  21. fixable: 'code',
  22. schema: [
  23. { enum: ['double', 'single'] }
  24. ]
  25. },
  26. create (context) {
  27. const sourceCode = context.getSourceCode()
  28. const double = context.options[0] !== 'single'
  29. const quoteChar = double ? '"' : "'"
  30. const quoteName = double ? 'double quotes' : 'single quotes'
  31. const quotePattern = double ? /"/g : /'/g
  32. const quoteEscaped = double ? '"' : '''
  33. let hasInvalidEOF
  34. return utils.defineTemplateBodyVisitor(context, {
  35. 'VAttribute[value!=null]' (node) {
  36. if (hasInvalidEOF) {
  37. return
  38. }
  39. const text = sourceCode.getText(node.value)
  40. const firstChar = text[0]
  41. if (firstChar !== quoteChar) {
  42. context.report({
  43. node: node.value,
  44. loc: node.value.loc,
  45. message: 'Expected to be enclosed by {{kind}}.',
  46. data: { kind: quoteName },
  47. fix (fixer) {
  48. const contentText = (firstChar === "'" || firstChar === '"') ? text.slice(1, -1) : text
  49. const replacement = quoteChar + contentText.replace(quotePattern, quoteEscaped) + quoteChar
  50. return fixer.replaceText(node.value, replacement)
  51. }
  52. })
  53. }
  54. }
  55. }, {
  56. Program (node) {
  57. hasInvalidEOF = utils.hasInvalidEOF(node)
  58. }
  59. })
  60. }
  61. }