no-redundant-roles.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. var _jsxAstUtils = require("jsx-ast-utils");
  4. var _arrayIncludes = _interopRequireDefault(require("array-includes"));
  5. var _has = _interopRequireDefault(require("has"));
  6. var _getExplicitRole = _interopRequireDefault(require("../util/getExplicitRole"));
  7. var _getImplicitRole = _interopRequireDefault(require("../util/getImplicitRole"));
  8. /**
  9. * @fileoverview Enforce explicit role property is not the
  10. * same as implicit/default role property on element.
  11. * @author Ethan Cohen <@evcohen>
  12. *
  13. */
  14. // ----------------------------------------------------------------------------
  15. // Rule Definition
  16. // ----------------------------------------------------------------------------
  17. var errorMessage = function errorMessage(element, implicitRole) {
  18. return "The element ".concat(element, " has an implicit role of ").concat(implicitRole, ". Defining this explicitly is redundant and should be avoided.");
  19. };
  20. var DEFAULT_ROLE_EXCEPTIONS = {
  21. nav: ['navigation']
  22. };
  23. module.exports = {
  24. meta: {
  25. docs: {
  26. url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/no-redundant-roles.md'
  27. },
  28. schema: [{
  29. type: 'object',
  30. additionalProperties: {
  31. type: 'array',
  32. items: {
  33. type: 'string'
  34. },
  35. uniqueItems: true
  36. }
  37. }]
  38. },
  39. create: function create(context) {
  40. var options = context.options;
  41. return {
  42. JSXOpeningElement: function JSXOpeningElement(node) {
  43. var type = (0, _jsxAstUtils.elementType)(node);
  44. var implicitRole = (0, _getImplicitRole["default"])(type, node.attributes);
  45. var explicitRole = (0, _getExplicitRole["default"])(type, node.attributes);
  46. if (!implicitRole || !explicitRole) {
  47. return;
  48. }
  49. if (implicitRole === explicitRole) {
  50. var allowedRedundantRoles = options[0] || {};
  51. var redundantRolesForElement;
  52. if ((0, _has["default"])(allowedRedundantRoles, type)) {
  53. redundantRolesForElement = allowedRedundantRoles[type];
  54. } else {
  55. redundantRolesForElement = DEFAULT_ROLE_EXCEPTIONS[type] || [];
  56. }
  57. if ((0, _arrayIncludes["default"])(redundantRolesForElement, implicitRole)) {
  58. return;
  59. }
  60. context.report({
  61. node,
  62. message: errorMessage(type, implicitRole.toLowerCase())
  63. });
  64. }
  65. }
  66. };
  67. }
  68. };