/
angularWhitespaceRule.ts
260 lines (219 loc) · 9.7 KB
/
angularWhitespaceRule.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import * as Lint from 'tslint';
import * as ts from 'typescript';
import {NgWalker} from './angular/ngWalker';
import * as ast from '@angular/compiler';
import {BasicTemplateAstVisitor} from './angular/templates/basicTemplateAstVisitor';
import {ExpTypes} from './angular/expressionTypes';
import {Config} from './angular/config';
import {RecursiveAngularExpressionVisitor} from './angular/templates/recursiveAngularExpressionVisitor';
const InterpolationOpen = Config.interpolation[0];
const InterpolationClose = Config.interpolation[1];
const InterpolationNoWhitespaceRe = new RegExp(`${InterpolationOpen}\\S(.*?)\\S${InterpolationClose}|${InterpolationOpen}` +
`\\s(.*?)\\S${InterpolationClose}|${InterpolationOpen}\\S(.*?)\\s${InterpolationClose}`);
const InterpolationExtraWhitespaceRe =
new RegExp(`${InterpolationOpen}\\s\\s(.*?)\\s${InterpolationClose}|${InterpolationOpen}\\s(.*?)\\s\\s${InterpolationClose}`);
const SemicolonNoWhitespaceNotInSimpleQuoteRe = new RegExp(/;\S(?![^']*')/);
const SemicolonNoWhitespaceNotInDoubleQuoteRe = new RegExp(/;\S(?![^"]*")/);
const getReplacements = (text: ast.BoundTextAst, absolutePosition: number) => {
const expr: string = (text.value as any).source;
const internalStart = expr.indexOf(InterpolationOpen);
const internalEnd = expr.lastIndexOf(InterpolationClose);
const len = expr.trim().length - InterpolationOpen.length - InterpolationClose.length;
const trimmed = expr.substr(internalStart + InterpolationOpen.length, len).trim();
return [
new Lint.Replacement(absolutePosition,
internalEnd - internalStart + InterpolationClose.length,
`${InterpolationOpen} ${trimmed} ${InterpolationClose}`)
];
};
const getSemicolonReplacements = (text: ast.BoundDirectivePropertyAst, absolutePosition: number) => {
return [
new Lint.Replacement(absolutePosition, 1, '; ')
];
};
type Option = 'check-interpolation' | 'check-pipe' | 'check-semicolon';
interface ConfigurableVisitor {
getOption(): Option;
}
/* Inrerpolation visitors */
class InterpolationWhitespaceVisitor extends BasicTemplateAstVisitor implements ConfigurableVisitor {
visitBoundText(text: ast.BoundTextAst, context: BasicTemplateAstVisitor): any {
if (ExpTypes.ASTWithSource(text.value)) {
// Note that will not be reliable for different interpolation symbols
let error = null;
const expr: any = (<any>text.value).source;
if (InterpolationNoWhitespaceRe.test(expr)) {
error = `Missing whitespace in interpolation; expecting ${InterpolationOpen} expr ${InterpolationClose}`;
}
if (InterpolationExtraWhitespaceRe.test(expr)) {
error = `Extra whitespace in interpolation; expecting ${InterpolationOpen} expr ${InterpolationClose}`;
}
if (error) {
const internalStart = expr.indexOf(InterpolationOpen);
const start = text.sourceSpan.start.offset + internalStart;
const absolutePosition = context.getSourcePosition(start);
return context.addFailure(
context.createFailure(start,
expr.trim().length,
error, getReplacements(text, absolutePosition)));
}
}
super.visitBoundText(text, context);
return null;
}
getOption(): Option {
return 'check-interpolation';
}
}
class SemicolonTemplateVisitor extends BasicTemplateAstVisitor implements ConfigurableVisitor {
visitDirectiveProperty(prop: ast.BoundDirectivePropertyAst, context: BasicTemplateAstVisitor): any {
if (prop.sourceSpan) {
const directive = (<any>prop.sourceSpan).toString();
const rawExpression = directive.split('=')[1].trim();
const expr = rawExpression.substring(1, rawExpression.length - 1).trim();
const doubleQuote = rawExpression.substring(0, 1).indexOf('\"') === 0;
// Note that will not be reliable for different interpolation symbols
let error = null;
if (doubleQuote && SemicolonNoWhitespaceNotInSimpleQuoteRe.test(expr)) {
error = 'Missing whitespace after semicolon; expecting \'; expr\'';
const internalStart = expr.search(SemicolonNoWhitespaceNotInSimpleQuoteRe) + 1;
const start = prop.sourceSpan.start.offset + internalStart + directive.length - directive.split('=')[1].trim().length + 1;
const absolutePosition = context.getSourcePosition(start - 1);
return context.addFailure(context.createFailure(start, 2,
error, getSemicolonReplacements(prop, absolutePosition))
);
} else if (!doubleQuote && SemicolonNoWhitespaceNotInDoubleQuoteRe.test(expr)) {
error = 'Missing whitespace after semicolon; expecting \'; expr\'';
const internalStart = expr.search(SemicolonNoWhitespaceNotInDoubleQuoteRe) + 1;
const start = prop.sourceSpan.start.offset + internalStart + directive.length - directive.split('=')[1].trim().length + 1;
const absolutePosition = context.getSourcePosition(start - 1);
return context.addFailure(context.createFailure(start, 2,
error, getSemicolonReplacements(prop, absolutePosition))
);
}
}
}
getOption(): Option {
return 'check-semicolon';
}
}
class WhitespaceTemplateVisitor extends BasicTemplateAstVisitor {
private visitors: (BasicTemplateAstVisitor & ConfigurableVisitor)[] = [
new InterpolationWhitespaceVisitor(this.getSourceFile(), this.getOptions(), this.context, this.templateStart),
new SemicolonTemplateVisitor(this.getSourceFile(), this.getOptions(), this.context, this.templateStart)
];
visitBoundText(text: ast.BoundTextAst, context: any): any {
const options = this.getOptions();
this.visitors
.filter(v => options.indexOf(v.getOption()) >= 0)
.map(v => v.visitBoundText(text, this))
.filter(f => !!f)
.forEach(f => this.addFailure(f));
super.visitBoundText(text, context);
}
visitDirectiveProperty(prop: ast.BoundDirectivePropertyAst, context: any): any {
const options = this.getOptions();
this.visitors
.filter(v => options.indexOf(v.getOption()) >= 0)
.map(v => v.visitDirectiveProperty(prop, this))
.filter(f => !!f)
.forEach(f => this.addFailure(f));
super.visitDirectiveProperty(prop, context);
}
}
/* Expression visitors */
class PipeWhitespaceVisitor extends RecursiveAngularExpressionVisitor implements ConfigurableVisitor {
visitPipe(ast: ast.BindingPipe, context: RecursiveAngularExpressionVisitor): any {
const start = ast.span.start;
const exprStart = context.getSourcePosition(ast.exp.span.start);
const exprEnd = context.getSourcePosition(ast.exp.span.end);
const sf = context.getSourceFile().getFullText();
const exprText = sf.substring(exprStart, exprEnd);
const replacements = [];
// Handling the right side of the pipe
let leftBeginning = exprEnd + 1; // exprEnd === '|'
if (sf[leftBeginning] === ' ') {
let ignoreSpace = 1;
while (sf[leftBeginning + ignoreSpace] === ' ') {
ignoreSpace += 1;
}
if (ignoreSpace > 1) {
replacements.push(new Lint.Replacement(exprEnd + 1, ignoreSpace, ' '));
}
} else {
replacements.push(new Lint.Replacement(exprEnd + 1, 0, ' '));
}
// Handling the left side of the pipe
if (exprText[exprText.length - 1] === ' ') {
let ignoreSpace = 1;
while (exprText[exprText.length - 1 - ignoreSpace] === ' ') {
ignoreSpace += 1;
}
if (ignoreSpace > 1) {
replacements.push(new Lint.Replacement(exprEnd - ignoreSpace, ignoreSpace, ' '));
}
} else {
replacements.push(new Lint.Replacement(exprEnd, 0, ' '));
}
if (replacements.length) {
context.addFailure(
context.createFailure(ast.exp.span.end - 1, 3,
'The pipe operator should be surrounded by one space on each side, i.e. " | ".',
replacements)
);
}
super.visitPipe(ast, context);
return null;
}
getOption(): Option {
return 'check-pipe';
}
protected isAsyncBinding(expr: any) {
return expr instanceof ast.BindingPipe && expr.name === 'async';
}
}
class TemplateExpressionVisitor extends RecursiveAngularExpressionVisitor {
private visitors: (RecursiveAngularExpressionVisitor & ConfigurableVisitor)[] = [
new PipeWhitespaceVisitor(this.getSourceFile(), this.getOptions(), this.context, this.basePosition)
];
visitPipe(expr: ast.BindingPipe, context: any): any {
const options = this.getOptions();
this.visitors
.filter(v => options.indexOf(v.getOption()) >= 0)
.map(v => v.visitPipe(expr, this))
.filter(f => !!f)
.forEach(f => this.addFailure(f));
}
}
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: Lint.IRuleMetadata = {
ruleName: 'angular-whitespace',
type: 'style',
description: `Ensures the proper formatting of Angular expressions.`,
rationale: `Having whitespace in the right places in an Angular expression makes the template more readable.`,
optionsDescription: Lint.Utils.dedent`
Arguments may be optionally provided:
* \`"check-interpolation"\` checks for whitespace before and after the interpolation characters
* \`"check-pipe"\` checks for whitespace before and after a pipe
* \`"check-semicolon"\` checks for whitespace after semicolon`,
options: {
type: 'array',
items: {
type: 'string',
enum: ['check-interpolation', 'check-pipe', 'check-semicolon'],
},
minLength: 0,
maxLength: 3,
},
optionExamples: ['[true, "check-interpolation"]'],
typescriptOnly: true,
};
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(
new NgWalker(sourceFile,
this.getOptions(), {
templateVisitorCtrl: WhitespaceTemplateVisitor,
expressionVisitorCtrl: TemplateExpressionVisitor,
}));
}
}