|
| 1 | +import { ElementAst } 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 | + |
| 7 | +export class Rule extends Rules.AbstractRule { |
| 8 | + static readonly metadata: IRuleMetadata = { |
| 9 | + description: 'Ensures that the click event is accompanied with at least one key event keyup, keydown or keypress', |
| 10 | + options: null, |
| 11 | + optionsDescription: 'Not configurable.', |
| 12 | + rationale: 'Keyboard is important for users with physical disabilities who cannot use mouse.', |
| 13 | + ruleName: 'template-click-events-have-key-events', |
| 14 | + type: 'functionality', |
| 15 | + typescriptOnly: true |
| 16 | + }; |
| 17 | + |
| 18 | + static readonly FAILURE_STRING = 'click must be accompanied by either keyup, keydown or keypress event for accessibility'; |
| 19 | + |
| 20 | + apply(sourceFile: SourceFile): RuleFailure[] { |
| 21 | + return this.applyWithWalker( |
| 22 | + new NgWalker(sourceFile, this.getOptions(), { |
| 23 | + templateVisitorCtrl: TemplateClickEventsHaveKeyEventsVisitor |
| 24 | + }) |
| 25 | + ); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +class TemplateClickEventsHaveKeyEventsVisitor extends BasicTemplateAstVisitor { |
| 30 | + visitElement(el: ElementAst, context: any) { |
| 31 | + this.validateElement(el); |
| 32 | + super.visitElement(el, context); |
| 33 | + } |
| 34 | + |
| 35 | + private validateElement(el: ElementAst): void { |
| 36 | + const hasClick = el.outputs.some(output => output.name === 'click'); |
| 37 | + if (!hasClick) { |
| 38 | + return; |
| 39 | + } |
| 40 | + const hasKeyEvent = el.outputs.some(output => output.name === 'keyup' || output.name === 'keydown' || output.name === 'keypress'); |
| 41 | + |
| 42 | + if (hasKeyEvent) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const { |
| 47 | + sourceSpan: { |
| 48 | + end: { offset: endOffset }, |
| 49 | + start: { offset: startOffset } |
| 50 | + } |
| 51 | + } = el; |
| 52 | + |
| 53 | + this.addFailureFromStartToEnd(startOffset, endOffset, Rule.FAILURE_STRING); |
| 54 | + } |
| 55 | +} |
0 commit comments