All files / src/rules element-name.ts

100% Statements 17/17
100% Branches 10/10
100% Functions 2/2
100% Lines 17/17
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 44 45 46 47 48 49 50 51      1x                       14x 14x 14x   14x 19x 19x     19x 1x         19x 9x         10x 3x       7x 1x     6x 3x        
import { Rule, RuleReport, RuleParserProxy } from '../rule';
import { TagOpenEvent } from '../event';
 
export = {
	name: 'element-name',
	init,
 
	defaults: {
		pattern: '^[a-z][a-z0-9\\-._]*-[a-z0-9\\-._]*$',
		whitelist: [],
		blacklist: [],
	},
} as Rule;
 
function init(parser: RuleParserProxy, userOptions: any){
	const options = Object.assign({}, this.defaults, userOptions);
	const regex = new RegExp(options.pattern);
	const xmlns = /^(.+):.+$/;
 
	parser.on('tag:open', (event: TagOpenEvent, report: RuleReport) => {
		const target = event.target;
		const tagName = target.tagName;
 
		/* check if element is blacklisted */
		if (options.blacklist.indexOf(tagName) >= 0){
			report(target, `<${tagName}> element is blacklisted`);
		}
 
		/* assume that an element with meta has valid name as it is a builtin
		 * element */
		if (target.meta){
			return;
		}
 
		/* ignore elements in xml namespaces, they should be validated against a
		 * DTD instead */
		if (tagName.match(xmlns)){
			return;
		}
 
		/* check if element is whitelisted */
		if (options.whitelist.indexOf(tagName) >= 0){
			return;
		}
 
		if (!tagName.match(regex)){
			report(target, `<${tagName}> is not a valid element name`);
		}
	});
}