|
| 1 | +import { ElementAst } from '@angular/compiler'; |
| 2 | +import { IRuleMetadata, RuleFailure, Rules, Utils } from 'tslint/lib'; |
| 3 | +import { SourceFile } from 'typescript'; |
| 4 | +import { NgWalker } from './angular/ngWalker'; |
| 5 | +import { BasicTemplateAstVisitor } from './angular'; |
| 6 | + |
| 7 | +class TemplateAccessibilityAnchorContentVisitor extends BasicTemplateAstVisitor { |
| 8 | + visitElement(ast: ElementAst, context: any) { |
| 9 | + this.validateElement(ast); |
| 10 | + super.visitElement(ast, context); |
| 11 | + } |
| 12 | + |
| 13 | + validateElement(element: ElementAst) { |
| 14 | + if (element.name !== 'a') { |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + const hasContent = element.children.length; |
| 19 | + const hasInnerContent = element.inputs.some(input => input.name === 'innerHTML' || input.name === 'innerText'); |
| 20 | + if (hasContent || hasInnerContent) { |
| 21 | + return; |
| 22 | + } |
| 23 | + const { |
| 24 | + sourceSpan: { |
| 25 | + end: { offset: endOffset }, |
| 26 | + start: { offset: startOffset } |
| 27 | + } |
| 28 | + } = element; |
| 29 | + this.addFailureFromStartToEnd(startOffset, endOffset, Rule.FAILURE_MESSAGE); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +export class Rule extends Rules.AbstractRule { |
| 34 | + static readonly metadata: IRuleMetadata = { |
| 35 | + description: 'Ensures that the anchor element has some content in it', |
| 36 | + options: null, |
| 37 | + optionsDescription: 'Not configurable.', |
| 38 | + rationale: 'Anchor elements should have content to be accessible by screen readers', |
| 39 | + ruleName: 'template-accessibility-anchor-content', |
| 40 | + type: 'functionality', |
| 41 | + typescriptOnly: true |
| 42 | + }; |
| 43 | + |
| 44 | + static readonly FAILURE_MESSAGE = 'Anchor element should have content'; |
| 45 | + |
| 46 | + apply(sourceFile: SourceFile): RuleFailure[] { |
| 47 | + return this.applyWithWalker( |
| 48 | + new NgWalker(sourceFile, this.getOptions(), { |
| 49 | + templateVisitorCtrl: TemplateAccessibilityAnchorContentVisitor |
| 50 | + }) |
| 51 | + ); |
| 52 | + } |
| 53 | +} |
0 commit comments