html-quotes.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. const utils = require('../utils')
  8. module.exports = {
  9. meta: {
  10. type: 'layout',
  11. docs: {
  12. description: 'enforce quotes style of HTML attributes',
  13. categories: ['vue3-strongly-recommended', 'strongly-recommended'],
  14. url: 'https://eslint.vuejs.org/rules/html-quotes.html'
  15. },
  16. fixable: 'code',
  17. schema: [
  18. { enum: ['double', 'single'] },
  19. {
  20. type: 'object',
  21. properties: {
  22. avoidEscape: {
  23. type: 'boolean'
  24. }
  25. },
  26. additionalProperties: false
  27. }
  28. ]
  29. },
  30. /** @param {RuleContext} context */
  31. create(context) {
  32. const sourceCode = context.getSourceCode()
  33. const double = context.options[0] !== 'single'
  34. const avoidEscape =
  35. context.options[1] && context.options[1].avoidEscape === true
  36. const quoteChar = double ? '"' : "'"
  37. const quoteName = double ? 'double quotes' : 'single quotes'
  38. /** @type {boolean} */
  39. let hasInvalidEOF
  40. return utils.defineTemplateBodyVisitor(
  41. context,
  42. {
  43. 'VAttribute[value!=null]'(node) {
  44. if (hasInvalidEOF) {
  45. return
  46. }
  47. const text = sourceCode.getText(node.value)
  48. const firstChar = text[0]
  49. if (firstChar !== quoteChar) {
  50. const quoted = firstChar === "'" || firstChar === '"'
  51. if (avoidEscape && quoted) {
  52. const contentText = text.slice(1, -1)
  53. if (contentText.includes(quoteChar)) {
  54. return
  55. }
  56. }
  57. context.report({
  58. node: node.value,
  59. loc: node.value.loc,
  60. message: 'Expected to be enclosed by {{kind}}.',
  61. data: { kind: quoteName },
  62. fix(fixer) {
  63. const contentText = quoted ? text.slice(1, -1) : text
  64. let fixToDouble = double
  65. if (avoidEscape && !quoted && contentText.includes(quoteChar)) {
  66. fixToDouble = double
  67. ? contentText.includes("'")
  68. : !contentText.includes('"')
  69. }
  70. const quotePattern = fixToDouble ? /"/g : /'/g
  71. const quoteEscaped = fixToDouble ? '"' : '''
  72. const fixQuoteChar = fixToDouble ? '"' : "'"
  73. const replacement =
  74. fixQuoteChar +
  75. contentText.replace(quotePattern, quoteEscaped) +
  76. fixQuoteChar
  77. return fixer.replaceText(node.value, replacement)
  78. }
  79. })
  80. }
  81. }
  82. },
  83. {
  84. Program(node) {
  85. hasInvalidEOF = utils.hasInvalidEOF(node)
  86. }
  87. }
  88. )
  89. }
  90. }