/
trackByFunctionRule.ts
74 lines (59 loc) · 2.47 KB
/
trackByFunctionRule.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
import { BoundDirectivePropertyAst } from '@angular/compiler';
import { IRuleMetadata, RuleFailure, Rules } from 'tslint/lib';
import { SourceFile } from 'typescript/lib/typescript';
import { NgWalker } from './angular/ngWalker';
import { BasicTemplateAstVisitor } from './angular/templates/basicTemplateAstVisitor';
//current offSet into the template
export let curOffSet = 0;
export class Rule extends Rules.AbstractRule {
static readonly metadata: IRuleMetadata = {
description: 'Ensures a trackBy function is used.',
options: null,
optionsDescription: 'Not configurable.',
rationale: "The use of 'trackBy' is considered a good practice.",
ruleName: 'trackBy-function',
type: 'maintainability',
typescriptOnly: true
};
static readonly FAILURE_STRING = 'Missing trackBy function in ngFor directive';
apply(sourceFile: SourceFile): RuleFailure[] {
curOffSet = 0;
return this.applyWithWalker(new NgWalker(sourceFile, this.getOptions(), { templateVisitorCtrl: TrackByTemplateVisitor }));
}
}
export const getFailureMessage = (): string => {
return Rule.FAILURE_STRING;
};
class TrackByFunctionTemplateVisitor extends BasicTemplateAstVisitor {
visitDirectiveProperty(prop: BoundDirectivePropertyAst, context: BasicTemplateAstVisitor): any {
this.validateDirective(prop, context);
super.visitDirectiveProperty(prop, context);
}
private validateDirective(prop: BoundDirectivePropertyAst, context: BasicTemplateAstVisitor): any {
const { templateName } = prop;
if (templateName !== 'ngForOf') {
return;
}
const pattern = /\s*ngFor.*\s*trackBy\s*:|\[ngForTrackBy\]\s*=\s*['"].*['"]/;
if (pattern.test(context.codeWithMap.source!.substr(curOffSet))) {
curOffSet = prop.sourceSpan.end.offset;
return;
}
const {
sourceSpan: {
end: { offset: endOffset },
start: { offset: startOffset }
}
} = prop;
context.addFailureFromStartToEnd(startOffset, endOffset, getFailureMessage());
}
}
class TrackByTemplateVisitor extends BasicTemplateAstVisitor {
private readonly visitors: ReadonlySet<BasicTemplateAstVisitor> = new Set([
new TrackByFunctionTemplateVisitor(this.getSourceFile(), this.getOptions(), this.context, this.templateStart)
]);
visitDirectiveProperty(prop: BoundDirectivePropertyAst, context: BasicTemplateAstVisitor): any {
this.visitors.forEach(visitor => visitor.visitDirectiveProperty(prop, this));
super.visitDirectiveProperty(prop, context);
}
}