UNPKG

d2-ui

Version:
81 lines (63 loc) 2.37 kB
/** * @fileoverview Enforce img tag uses alt attribute. * @author Ethan Cohen */ 'use strict'; // ---------------------------------------------------------------------------- // Rule Definition // ---------------------------------------------------------------------------- var _getAttribute = require('../util/getAttribute'); var _getAttribute2 = _interopRequireDefault(_getAttribute); var _getAttributeValue = require('../util/getAttributeValue'); var _getAttributeValue2 = _interopRequireDefault(_getAttributeValue); var _getNodeType = require('../util/getNodeType'); var _getNodeType2 = _interopRequireDefault(_getNodeType); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = function (context) { return { JSXOpeningElement: function JSXOpeningElement(node) { var typeCheck = ['img'].concat(context.options[0]); var nodeType = (0, _getNodeType2.default)(node); // Only check 'img' elements and custom types. if (typeCheck.indexOf(nodeType) === -1) { return; } var roleProp = (0, _getAttribute2.default)(node.attributes, 'role'); var roleValue = (0, _getAttributeValue2.default)(roleProp); var isPresentation = roleProp && typeof roleValue === 'string' && roleValue.toLowerCase() === 'presentation'; if (isPresentation) { return; } var altProp = (0, _getAttribute2.default)(node.attributes, 'alt'); // Missing alt prop error. if (altProp === undefined) { context.report({ node: node, message: nodeType + ' elements must have an alt prop or use role="presentation".' }); return; } // Check if alt prop is undefined. var altValue = (0, _getAttributeValue2.default)(altProp); var isNullValued = altProp.value === null; // <img alt /> if (altValue && !isNullValued || altValue === '') { return; } // Undefined alt prop error. context.report({ node: node, message: 'Invalid alt value for ' + nodeType + '. Use alt="" or role="presentation" for presentational images.' }); } }; }; module.exports.schema = [{ 'oneOf': [{ 'type': 'string' }, { 'type': 'array', 'items': { 'type': 'string' }, 'minItems': 1, 'uniqueItems': true }] }];