aria-role.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  4. var _ariaQuery = require("aria-query");
  5. var _jsxAstUtils = require("jsx-ast-utils");
  6. var _schemas = require("../util/schemas");
  7. /**
  8. * @fileoverview Enforce aria role attribute is valid.
  9. * @author Ethan Cohen
  10. */
  11. // ----------------------------------------------------------------------------
  12. // Rule Definition
  13. // ----------------------------------------------------------------------------
  14. var errorMessage = 'Elements with ARIA roles must use a valid, non-abstract ARIA role.';
  15. var schema = (0, _schemas.generateObjSchema)({
  16. ignoreNonDOM: {
  17. type: 'boolean',
  18. "default": false
  19. }
  20. });
  21. module.exports = {
  22. meta: {
  23. docs: {
  24. url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/aria-role.md'
  25. },
  26. schema: [schema]
  27. },
  28. create: function create(context) {
  29. return {
  30. JSXAttribute: function JSXAttribute(attribute) {
  31. // Determine if ignoreNonDOM is set to true
  32. // If true, then do not run rule.
  33. var options = context.options[0] || {};
  34. var ignoreNonDOM = !!options.ignoreNonDOM;
  35. if (ignoreNonDOM) {
  36. var type = (0, _jsxAstUtils.elementType)(attribute.parent);
  37. if (!_ariaQuery.dom.get(type)) {
  38. return;
  39. }
  40. } // Get prop name
  41. var name = (0, _jsxAstUtils.propName)(attribute).toUpperCase();
  42. if (name !== 'ROLE') {
  43. return;
  44. }
  45. var value = (0, _jsxAstUtils.getLiteralPropValue)(attribute); // If value is undefined, then the role attribute will be dropped in the DOM.
  46. // If value is null, then getLiteralAttributeValue is telling us that the
  47. // value isn't in the form of a literal.
  48. if (value === undefined || value === null) {
  49. return;
  50. }
  51. var values = String(value).split(' ');
  52. var validRoles = (0, _toConsumableArray2["default"])(_ariaQuery.roles.keys()).filter(function (role) {
  53. return _ariaQuery.roles.get(role)["abstract"] === false;
  54. });
  55. var isValid = values.every(function (val) {
  56. return validRoles.indexOf(val) > -1;
  57. });
  58. if (isValid === true) {
  59. return;
  60. }
  61. context.report({
  62. node: attribute,
  63. message: errorMessage
  64. });
  65. }
  66. };
  67. }
  68. };