html-quotes.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. messages: {
  30. expected: 'Expected to be enclosed by {{kind}}.'
  31. }
  32. },
  33. /** @param {RuleContext} context */
  34. create(context) {
  35. const sourceCode = context.getSourceCode()
  36. const double = context.options[0] !== 'single'
  37. const avoidEscape =
  38. context.options[1] && context.options[1].avoidEscape === true
  39. const quoteChar = double ? '"' : "'"
  40. const quoteName = double ? 'double quotes' : 'single quotes'
  41. /** @type {boolean} */
  42. let hasInvalidEOF
  43. return utils.defineTemplateBodyVisitor(
  44. context,
  45. {
  46. 'VAttribute[value!=null]'(node) {
  47. if (hasInvalidEOF) {
  48. return
  49. }
  50. const text = sourceCode.getText(node.value)
  51. const firstChar = text[0]
  52. if (firstChar !== quoteChar) {
  53. const quoted = firstChar === "'" || firstChar === '"'
  54. if (avoidEscape && quoted) {
  55. const contentText = text.slice(1, -1)
  56. if (contentText.includes(quoteChar)) {
  57. return
  58. }
  59. }
  60. context.report({
  61. node: node.value,
  62. loc: node.value.loc,
  63. messageId: 'expected',
  64. data: { kind: quoteName },
  65. fix(fixer) {
  66. const contentText = quoted ? text.slice(1, -1) : text
  67. let fixToDouble = double
  68. if (avoidEscape && !quoted && contentText.includes(quoteChar)) {
  69. fixToDouble = double
  70. ? contentText.includes("'")
  71. : !contentText.includes('"')
  72. }
  73. const quotePattern = fixToDouble ? /"/g : /'/g
  74. const quoteEscaped = fixToDouble ? '"' : '''
  75. const fixQuoteChar = fixToDouble ? '"' : "'"
  76. const replacement =
  77. fixQuoteChar +
  78. contentText.replace(quotePattern, quoteEscaped) +
  79. fixQuoteChar
  80. return fixer.replaceText(node.value, replacement)
  81. }
  82. })
  83. }
  84. }
  85. },
  86. {
  87. Program(node) {
  88. hasInvalidEOF = utils.hasInvalidEOF(node)
  89. }
  90. }
  91. )
  92. }
  93. }