|
| 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 Mouse Events mouseover and mouseout are accompanied with Key Events focus and blur', |
| 10 | + options: null, |
| 11 | + optionsDescription: 'Not configurable.', |
| 12 | + rationale: 'Keyboard is important for users with physical disabilities who cannot use mouse.', |
| 13 | + ruleName: 'template-mouse-events-have-key-events', |
| 14 | + type: 'functionality', |
| 15 | + typescriptOnly: true |
| 16 | + }; |
| 17 | + |
| 18 | + static readonly FAILURE_STRING_MOUSE_OVER = 'mouseover must be accompanied by focus event for accessibility'; |
| 19 | + static readonly FAILURE_STRING_MOUSE_OUT = 'mouseout must be accompanied by blur event for accessibility'; |
| 20 | + |
| 21 | + apply(sourceFile: SourceFile): RuleFailure[] { |
| 22 | + return this.applyWithWalker( |
| 23 | + new NgWalker(sourceFile, this.getOptions(), { |
| 24 | + templateVisitorCtrl: TemplateMouseEventsHaveKeyEventsVisitor |
| 25 | + }) |
| 26 | + ); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +class TemplateMouseEventsHaveKeyEventsVisitor extends BasicTemplateAstVisitor { |
| 31 | + visitElement(el: ElementAst, context: any) { |
| 32 | + this.validateElement(el); |
| 33 | + super.visitElement(el, context); |
| 34 | + } |
| 35 | + |
| 36 | + private validateElement(el: ElementAst): void { |
| 37 | + const hasMouseOver = el.outputs.some(output => output.name === 'mouseover'); |
| 38 | + const hasMouseOut = el.outputs.some(output => output.name === 'mouseout'); |
| 39 | + const hasFocus = el.outputs.some(output => output.name === 'focus'); |
| 40 | + const hasBlur = el.outputs.some(output => output.name === 'blur'); |
| 41 | + |
| 42 | + if (!hasMouseOver && !hasMouseOut) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const { |
| 47 | + sourceSpan: { |
| 48 | + end: { offset: endOffset }, |
| 49 | + start: { offset: startOffset } |
| 50 | + } |
| 51 | + } = el; |
| 52 | + |
| 53 | + if (hasMouseOver && !hasFocus) { |
| 54 | + this.addFailureFromStartToEnd(startOffset, endOffset, Rule.FAILURE_STRING_MOUSE_OVER); |
| 55 | + } |
| 56 | + |
| 57 | + if (hasMouseOut && !hasBlur) { |
| 58 | + this.addFailureFromStartToEnd(startOffset, endOffset, Rule.FAILURE_STRING_MOUSE_OUT); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments