All files / src/rules img-req-alt.ts

100% Statements 14/14
100% Branches 9/9
100% Functions 3/3
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43        1x                     12x     12x 2x     12x 12x 12x   9x 9x 3x       6x 3x 2x       4x        
import { Rule, RuleReport, RuleParserProxy } from '../rule';
import { DOMNode } from 'dom';
import { DOMReadyEvent } from '../event';
 
export = {
	name: 'img-req-alt',
	init,
 
	defaults: {
		allowEmpty: true,
		alias: [],
	},
} as Rule;
 
function init(parser: RuleParserProxy, options: any){
	this.options = Object.assign(this.defaults, options);
 
	/* ensure alias is array */
	if (!Array.isArray(this.options.alias)){
		this.options.alias = [this.options.alias];
	}
 
	parser.on('dom:ready', (event: DOMReadyEvent, report: RuleReport) => {
		const images = event.document.getElementsByTagName('img');
		images.forEach((node: DOMNode) => {
			/* validate plain alt-attribute */
			const alt = node.getAttribute('alt');
			if (alt || (alt === "" && this.options.allowEmpty)){
				return;
			}
 
			/* validate if any non-empty alias is present */
			for (const attr of this.options.alias){
				if (node.getAttribute(attr)){
					return;
				}
			}
 
			report(node, "<img> is missing required alt attribute");
		});
	});
}