|
| 1 | +import { AttrAst, BoundElementPropertyAst } from '@angular/compiler'; |
| 2 | +import { IRuleMetadata, RuleFailure, Rules } from 'tslint/lib'; |
| 3 | +import { SourceFile } from 'typescript/lib/typescript'; |
| 4 | +import { NgWalker } from './angular/ngWalker'; |
| 5 | +import { BasicTemplateAstVisitor } from './angular/templates/basicTemplateAstVisitor'; |
| 6 | +import { aria } from 'aria-query'; |
| 7 | +import { getSuggestion } from './util/getSuggestion'; |
| 8 | + |
| 9 | +const ariaAttributes: string[] = [...(<string[]>Array.from(aria.keys()))]; |
| 10 | + |
| 11 | +export class Rule extends Rules.AbstractRule { |
| 12 | + static readonly metadata: IRuleMetadata = { |
| 13 | + description: 'Ensures that the correct ARIA attributes are used', |
| 14 | + options: null, |
| 15 | + optionsDescription: 'Not configurable.', |
| 16 | + rationale: 'Elements should not use invalid aria attributes (AX_ARIA_11)', |
| 17 | + ruleName: 'template-accessibility-valid-aria', |
| 18 | + type: 'functionality', |
| 19 | + typescriptOnly: true |
| 20 | + }; |
| 21 | + |
| 22 | + apply(sourceFile: SourceFile): RuleFailure[] { |
| 23 | + return this.applyWithWalker( |
| 24 | + new NgWalker(sourceFile, this.getOptions(), { |
| 25 | + templateVisitorCtrl: TemplateAccessibilityValidAriaVisitor |
| 26 | + }) |
| 27 | + ); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export const getFailureMessage = (name: string): string => { |
| 32 | + const suggestions = getSuggestion(name, ariaAttributes); |
| 33 | + const message = `${name}: This attribute is an invalid ARIA attribute.`; |
| 34 | + |
| 35 | + if (suggestions.length > 0) { |
| 36 | + return `${message} Did you mean to use ${suggestions}?`; |
| 37 | + } |
| 38 | + |
| 39 | + return message; |
| 40 | +}; |
| 41 | + |
| 42 | +class TemplateAccessibilityValidAriaVisitor extends BasicTemplateAstVisitor { |
| 43 | + visitAttr(ast: AttrAst, context: any) { |
| 44 | + this.validateAttribute(ast); |
| 45 | + super.visitAttr(ast, context); |
| 46 | + } |
| 47 | + |
| 48 | + visitElementProperty(ast: BoundElementPropertyAst) { |
| 49 | + this.validateAttribute(ast); |
| 50 | + super.visitElementProperty(ast, context); |
| 51 | + } |
| 52 | + |
| 53 | + private validateAttribute(ast: AttrAst | BoundElementPropertyAst) { |
| 54 | + if (ast.name.indexOf('aria-') !== 0) return; |
| 55 | + const isValid = ariaAttributes.indexOf(ast.name) > -1; |
| 56 | + if (isValid) return; |
| 57 | + |
| 58 | + const { |
| 59 | + sourceSpan: { |
| 60 | + end: { offset: endOffset }, |
| 61 | + start: { offset: startOffset } |
| 62 | + } |
| 63 | + } = ast; |
| 64 | + this.addFailureFromStartToEnd(startOffset, endOffset, getFailureMessage(ast.name)); |
| 65 | + } |
| 66 | +} |
0 commit comments