forked from mgechev/codelyzer
/
templateClickEventsHaveKeyEventsRule.ts
76 lines (63 loc) · 2.5 KB
/
templateClickEventsHaveKeyEventsRule.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { ElementAst } from '@angular/compiler';
import { dom } from 'aria-query';
import { IRuleMetadata, RuleFailure, Rules } from 'tslint/lib';
import { SourceFile } from 'typescript/lib/typescript';
import { NgWalker, NgWalkerConfig } from './angular/ngWalker';
import { BasicTemplateAstVisitor } from './angular/templates/basicTemplateAstVisitor';
import { isHiddenFromScreenReader } from './util/isHiddenFromScreenReader';
import { isInteractiveElement } from './util/isInteractiveElement';
import { isPresentationRole } from './util/isPresentationRole';
const domElements = new Set(dom.keys());
export class Rule extends Rules.AbstractRule {
static readonly metadata: IRuleMetadata = {
description: 'Ensures that the click event is accompanied with at least one key event keyup, keydown or keypress',
options: null,
optionsDescription: 'Not configurable.',
rationale: 'Keyboard is important for users with physical disabilities who cannot use mouse.',
ruleName: 'template-click-events-have-key-events',
type: 'functionality',
typescriptOnly: true
};
static readonly FAILURE_STRING = 'click must be accompanied by either keyup, keydown or keypress event for accessibility';
apply(sourceFile: SourceFile): RuleFailure[] {
const walkerConfig: NgWalkerConfig = { templateVisitorCtrl: TemplateVisitorCtrl };
const walker = new NgWalker(sourceFile, this.getOptions(), walkerConfig);
return this.applyWithWalker(walker);
}
}
class TemplateVisitorCtrl extends BasicTemplateAstVisitor {
visitElement(el: ElementAst, context: any) {
this.validateElement(el);
super.visitElement(el, context);
}
private validateElement(el: ElementAst): void {
const hasClick = el.outputs.some(output => output.name === 'click');
if (!hasClick) {
return;
}
if (!domElements.has(el.name)) {
// Do not test components, as we do not know what
// low-level DOM element this maps to.
return;
}
if (isPresentationRole(el) || isHiddenFromScreenReader(el)) {
return;
}
if (isInteractiveElement(el)) {
return;
}
const hasKeyEvent = el.outputs.some(
output => output.name.startsWith('keyup') || output.name.startsWith('keydown') || output.name.startsWith('keypress')
);
if (hasKeyEvent) {
return;
}
const {
sourceSpan: {
end: { offset: endOffset },
start: { offset: startOffset }
}
} = el;
this.addFailureFromStartToEnd(startOffset, endOffset, Rule.FAILURE_STRING);
}
}