forbid-dom-props.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * @fileoverview Forbid certain props on DOM Nodes
  3. * @author David Vázquez
  4. */
  5. 'use strict';
  6. const docsUrl = require('../util/docsUrl');
  7. // ------------------------------------------------------------------------------
  8. // Constants
  9. // ------------------------------------------------------------------------------
  10. const DEFAULTS = [];
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. docs: {
  17. description: 'Forbid certain props on DOM Nodes',
  18. category: 'Best Practices',
  19. recommended: false,
  20. url: docsUrl('forbid-dom-props')
  21. },
  22. messages: {
  23. propIsForbidden: 'Prop "{{prop}}" is forbidden on DOM Nodes'
  24. },
  25. schema: [{
  26. type: 'object',
  27. properties: {
  28. forbid: {
  29. type: 'array',
  30. items: {
  31. oneOf: [{
  32. type: 'string'
  33. }, {
  34. type: 'object',
  35. properties: {
  36. propName: {
  37. type: 'string'
  38. },
  39. message: {
  40. type: 'string'
  41. }
  42. }
  43. }],
  44. minLength: 1
  45. },
  46. uniqueItems: true
  47. }
  48. },
  49. additionalProperties: false
  50. }]
  51. },
  52. create(context) {
  53. const configuration = context.options[0] || {};
  54. const forbid = new Map((configuration.forbid || DEFAULTS).map((value) => {
  55. const propName = typeof value === 'string' ? value : value.propName;
  56. const options = {
  57. message: typeof value === 'string' ? null : value.message
  58. };
  59. return [propName, options];
  60. }));
  61. function isForbidden(prop) {
  62. return forbid.has(prop);
  63. }
  64. return {
  65. JSXAttribute(node) {
  66. const tag = node.parent.name.name;
  67. if (!(tag && typeof tag === 'string' && tag[0] !== tag[0].toUpperCase())) {
  68. // This is a Component, not a DOM node, so exit.
  69. return;
  70. }
  71. const prop = node.name.name;
  72. if (!isForbidden(prop)) {
  73. return;
  74. }
  75. const customMessage = forbid.get(prop).message;
  76. context.report(Object.assign({
  77. node,
  78. data: {
  79. prop
  80. }
  81. }, customMessage ? {message: customMessage} : {messageId: 'propIsForbidden'}));
  82. }
  83. };
  84. }
  85. };