img-redundant-alt.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. var _jsxAstUtils = require("jsx-ast-utils");
  4. var _schemas = require("../util/schemas");
  5. var _isHiddenFromScreenReader = _interopRequireDefault(require("../util/isHiddenFromScreenReader"));
  6. /**
  7. * @fileoverview Enforce img alt attribute does not have the word image, picture, or photo.
  8. * @author Ethan Cohen
  9. */
  10. // ----------------------------------------------------------------------------
  11. // Rule Definition
  12. // ----------------------------------------------------------------------------
  13. var REDUNDANT_WORDS = ['image', 'photo', 'picture'];
  14. var errorMessage = 'Redundant alt attribute. Screen-readers already announce `img` tags as an image. You don’t need to use the words `image`, `photo,` or `picture` (or any specified custom words) in the alt prop.';
  15. var schema = (0, _schemas.generateObjSchema)({
  16. components: _schemas.arraySchema,
  17. words: _schemas.arraySchema
  18. });
  19. module.exports = {
  20. meta: {
  21. docs: {
  22. url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/img-redundant-alt.md'
  23. },
  24. schema: [schema]
  25. },
  26. create: function create(context) {
  27. return {
  28. JSXOpeningElement: function JSXOpeningElement(node) {
  29. var options = context.options[0] || {};
  30. var componentOptions = options.components || [];
  31. var typesToValidate = ['img'].concat(componentOptions);
  32. var nodeType = (0, _jsxAstUtils.elementType)(node); // Only check 'label' elements and custom types.
  33. if (typesToValidate.indexOf(nodeType) === -1) {
  34. return;
  35. }
  36. var altProp = (0, _jsxAstUtils.getProp)(node.attributes, 'alt'); // Return if alt prop is not present.
  37. if (altProp === undefined) {
  38. return;
  39. }
  40. var value = (0, _jsxAstUtils.getLiteralPropValue)(altProp);
  41. var isVisible = (0, _isHiddenFromScreenReader["default"])(nodeType, node.attributes) === false;
  42. var _options$words = options.words,
  43. words = _options$words === void 0 ? [] : _options$words;
  44. var redundantWords = REDUNDANT_WORDS.concat(words);
  45. if (typeof value === 'string' && isVisible) {
  46. var hasRedundancy = new RegExp("(?!{)\\b(".concat(redundantWords.join('|'), ")\\b(?!})"), 'i').test(value);
  47. if (hasRedundancy === true) {
  48. context.report({
  49. node,
  50. message: errorMessage
  51. });
  52. }
  53. }
  54. }
  55. };
  56. }
  57. };