should-unescape-trans.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. module.exports = {
  2. meta: {
  3. type: 'problem',
  4. fixable: 'code',
  5. docs: {
  6. description: 'Ensure that Trans with values has shouldUnescape',
  7. },
  8. },
  9. create(context) {
  10. return {
  11. 'JSXOpeningElement[name.name="Trans"]'(node) {
  12. const attributes = new Map(
  13. node.attributes.map(attr => [attr.name.name, attr])
  14. )
  15. if (attributes.has('values') && !attributes.has('shouldUnescape')) {
  16. context.report({
  17. node,
  18. message: 'Trans with values must have shouldUnescape',
  19. fix(fixer) {
  20. return fixer.insertTextAfter(
  21. attributes.get('values'),
  22. '\nshouldUnescape' // Note: Prettier can fix indentation
  23. )
  24. },
  25. })
  26. }
  27. if (attributes.has('values') && attributes.has('shouldUnescape')) {
  28. const tOptions = attributes.get('tOptions')
  29. if (!tOptions) {
  30. context.report({
  31. node,
  32. message:
  33. 'Trans with shouldUnescape must have tOptions.interpolation.escapeValue',
  34. fix(fixer) {
  35. return fixer.insertTextAfter(
  36. attributes.get('shouldUnescape'),
  37. '\ntOptions={{ interpolation: { escapeValue: true } }}' // Note: Prettier can fix indentation
  38. )
  39. },
  40. })
  41. } else {
  42. const property = tOptions.value.expression.properties
  43. .find(p => p.key.name === 'interpolation')
  44. ?.value.properties.find(p => p.key.name === 'escapeValue')
  45. if (property?.value.value !== true) {
  46. context.report({
  47. node,
  48. message:
  49. 'Trans with shouldUnescape must have tOptions.interpolation.escapeValue set to true',
  50. })
  51. }
  52. }
  53. }
  54. },
  55. }
  56. },
  57. }