forked from angular-eslint/angular-eslint
/
attributes-order.ts
368 lines (329 loc) · 11 KB
/
attributes-order.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import type {
TmplAstElement,
TmplAstBoundAttribute,
TmplAstBoundEvent,
TmplAstReference,
TmplAstTextAttribute,
TmplAstNode,
} from '@angular-eslint/bundled-angular-compiler';
import { TmplAstTemplate } from '@angular-eslint/bundled-angular-compiler';
import { getTemplateParserServices } from '@angular-eslint/utils';
import type { TSESTree } from '@typescript-eslint/utils';
import { createESLintRule } from '../utils/create-eslint-rule';
export const enum OrderType {
TemplateReferenceVariable = 'TEMPLATE_REFERENCE',
StructuralDirective = 'STRUCTURAL_DIRECTIVE',
AttributeBinding = 'ATTRIBUTE_BINDING',
InputBinding = 'INPUT_BINDING',
OutputBinding = 'OUTPUT_BINDING',
TwoWayBinding = 'TWO_WAY_BINDING',
}
type Options = [
{
readonly alphabetical: boolean;
readonly order: readonly OrderType[];
},
];
type HasOrderType<Type extends OrderType> = Readonly<{
orderType: Type;
}>;
interface HasTemplateParent {
parent: TmplAstTemplate;
}
type ExtendedTmplAstBoundAttribute = TmplAstBoundAttribute &
HasOrderType<
| OrderType.InputBinding
| OrderType.TwoWayBinding
| OrderType.StructuralDirective
>;
type ExtendedTmplAstBoundEvent = TmplAstBoundEvent &
HasOrderType<OrderType.OutputBinding>;
type ExtendedTmplAstTextAttribute = TmplAstTextAttribute &
HasOrderType<OrderType.AttributeBinding | OrderType.StructuralDirective>;
type ExtendedTmplAstReference = TmplAstReference &
HasOrderType<OrderType.TemplateReferenceVariable>;
type ExtendedTmplAstElement = TmplAstElement & HasTemplateParent;
type ExtendedAttribute =
| ExtendedTmplAstBoundAttribute
| ExtendedTmplAstBoundEvent
| ExtendedTmplAstTextAttribute
| ExtendedTmplAstReference;
export type MessageIds = 'attributesOrder';
export const RULE_NAME = 'attributes-order';
const DEFAULT_ORDER = [
OrderType.StructuralDirective,
OrderType.TemplateReferenceVariable,
OrderType.AttributeBinding,
OrderType.InputBinding,
OrderType.TwoWayBinding,
OrderType.OutputBinding,
];
const DEFAULT_OPTIONS: Options[number] = {
alphabetical: false,
order: [...DEFAULT_ORDER],
};
export default createESLintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'layout',
docs: {
description:
'Ensures that HTML attributes and Angular bindings are sorted based on an expected order',
recommended: false,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
alphabetical: {
type: 'boolean',
default: DEFAULT_OPTIONS.alphabetical,
},
order: {
type: 'array',
items: {
enum: DEFAULT_OPTIONS.order,
},
default: DEFAULT_OPTIONS.order,
minItems: DEFAULT_OPTIONS.order.length,
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
attributesOrder: `The element's attributes/bindings did not match the expected order: expected {{expected}} instead of {{actual}}`,
},
},
defaultOptions: [DEFAULT_OPTIONS],
create(context, [{ alphabetical, order }]) {
const parserServices = getTemplateParserServices(context);
function getLocation(attr: ExtendedAttribute): TSESTree.SourceLocation {
const loc = parserServices.convertNodeSourceSpanToLoc(attr.sourceSpan);
switch (attr.orderType) {
case OrderType.StructuralDirective:
return {
start: {
line: loc.start.line,
column: loc.start.column - 1,
},
end: {
line: loc.end.line,
column: loc.end.column + 1,
},
};
default:
return loc;
}
}
return {
Element$1(node: ExtendedTmplAstElement) {
const { attributes, inputs, outputs, references } = node;
const { extractedBananaBoxes, extractedInputs, extractedOutputs } =
normalizeInputsOutputs(
inputs.map(toInputBindingOrderType),
outputs.map(toOutputBindingOrderType),
);
const allAttributes = [
...extractTemplateAttrs(node),
...attributes.map(toAttributeBindingOrderType),
...references.map(toTemplateReferenceVariableOrderType),
...extractedBananaBoxes,
...extractedInputs,
...extractedOutputs,
] as const;
if (allAttributes.length < 2) {
return;
}
const sortedAttributes = [...allAttributes].sort(byLocation);
const expectedAttributes = [...allAttributes].sort(
byOrder(order, alphabetical),
);
let errorRange: [number, number] | undefined;
for (let i = 0; i < sortedAttributes.length; i++) {
if (sortedAttributes[i] !== expectedAttributes[i]) {
errorRange = [errorRange?.[0] ?? i, i];
}
}
if (errorRange) {
const [startIndex, endIndex] = errorRange;
const sourceCode = context.getSourceCode();
const { start } = getLocation(sortedAttributes[startIndex]);
const { end } = getLocation(sortedAttributes[endIndex]);
const loc = { start, end };
const range = [
getStartPos(sortedAttributes[startIndex]),
getEndPos(sortedAttributes[endIndex]),
] as const;
let replacementText = '';
let lastPos = range[0];
for (let i = startIndex; i <= endIndex; i++) {
const oldAttr = sortedAttributes[i];
const oldStart = getStartPos(oldAttr);
const oldEnd = getEndPos(oldAttr);
const newAttr = expectedAttributes[i];
const newStart = getStartPos(newAttr);
const newEnd = getEndPos(newAttr);
replacementText += sourceCode.text.slice(lastPos, oldStart);
replacementText += sourceCode.text.slice(newStart, newEnd);
lastPos = oldEnd;
}
context.report({
loc,
messageId: 'attributesOrder',
data: {
expected: expectedAttributes
.slice(startIndex, endIndex + 1)
.map((a) => `\`${getMessageName(a)}\``)
.join(', '),
actual: sortedAttributes
.slice(startIndex, endIndex + 1)
.map((a) => `\`${getMessageName(a)}\``)
.join(', '),
},
fix: (fixer) => fixer.replaceTextRange(range, replacementText),
});
}
},
};
},
});
function byLocation(one: ExtendedAttribute, other: ExtendedAttribute) {
return one.sourceSpan.start.line === other.sourceSpan.start.line
? one.sourceSpan.start.col - other.sourceSpan.start.col
: one.sourceSpan.start.line - other.sourceSpan.start.line;
}
function byOrder(order: readonly OrderType[], alphabetical: boolean) {
return function (one: ExtendedAttribute, other: ExtendedAttribute) {
const orderComparison =
getOrderIndex(one, order) - getOrderIndex(other, order);
if (alphabetical && orderComparison === 0) {
return one.name > other.name ? 1 : -1;
}
return orderComparison;
};
}
function getOrderIndex(attr: ExtendedAttribute, order: readonly OrderType[]) {
return order.indexOf(attr.orderType);
}
function toAttributeBindingOrderType(attribute: TmplAstTextAttribute) {
return {
...attribute,
orderType: OrderType.AttributeBinding,
} as ExtendedTmplAstTextAttribute;
}
function toInputBindingOrderType(input: TmplAstBoundAttribute) {
return {
...input,
orderType: OrderType.InputBinding,
} as ExtendedTmplAstBoundAttribute;
}
function toStructuralDirectiveOrderType(
attributeOrInput: TmplAstBoundAttribute | TmplAstTextAttribute,
) {
return {
...attributeOrInput,
orderType: OrderType.StructuralDirective,
} as ExtendedTmplAstBoundAttribute | ExtendedTmplAstTextAttribute;
}
function toOutputBindingOrderType(output: TmplAstBoundEvent) {
return {
...output,
orderType: OrderType.OutputBinding,
} as ExtendedTmplAstBoundEvent;
}
function toTwoWayBindingOrderType(output: TmplAstBoundAttribute) {
return {
...output,
orderType: OrderType.TwoWayBinding,
} as ExtendedTmplAstBoundAttribute;
}
function toTemplateReferenceVariableOrderType(reference: TmplAstReference) {
return {
...reference,
orderType: OrderType.TemplateReferenceVariable,
} as ExtendedTmplAstReference;
}
function extractTemplateAttrs(
node: ExtendedTmplAstElement,
): (ExtendedTmplAstBoundAttribute | ExtendedTmplAstTextAttribute)[] {
return isTmplAstTemplate(node.parent)
? node.parent.templateAttrs.map(toStructuralDirectiveOrderType)
: [];
}
function normalizeInputsOutputs(
inputs: readonly TmplAstBoundAttribute[],
outputs: readonly TmplAstBoundEvent[],
) {
const extractedInputs: readonly ExtendedTmplAstBoundAttribute[] = inputs
.filter(
(input) => !outputs.some((output) => isOnSameLocation(input, output)),
)
.map(toInputBindingOrderType);
const { extractedBananaBoxes, extractedOutputs } = outputs.reduce<{
extractedOutputs: readonly ExtendedTmplAstBoundEvent[];
extractedBananaBoxes: readonly ExtendedTmplAstBoundAttribute[];
}>(
({ extractedBananaBoxes, extractedOutputs }, output) => {
const boundInput = inputs.find((input) =>
isOnSameLocation(input, output),
);
return {
extractedBananaBoxes: extractedBananaBoxes.concat(
boundInput ? toTwoWayBindingOrderType(boundInput) : [],
),
extractedOutputs: extractedOutputs.concat(
boundInput ? [] : toOutputBindingOrderType(output),
),
};
},
{ extractedBananaBoxes: [], extractedOutputs: [] },
);
return { extractedBananaBoxes, extractedInputs, extractedOutputs } as const;
}
function isTmplAstTemplate(node: TmplAstNode): node is TmplAstTemplate {
return node instanceof TmplAstTemplate;
}
function isOnSameLocation(
input: TmplAstBoundAttribute,
output: TmplAstBoundEvent,
) {
return (
input.sourceSpan.start === output.sourceSpan.start &&
input.sourceSpan.end === output.sourceSpan.end
);
}
function getMessageName(expected: ExtendedAttribute): string {
switch (expected.orderType) {
case OrderType.StructuralDirective:
return `*${expected.name}`;
case OrderType.TemplateReferenceVariable:
return `#${expected.name}`;
case OrderType.InputBinding:
return `[${expected.name}]`;
case OrderType.OutputBinding:
return `(${expected.name})`;
case OrderType.TwoWayBinding:
return `[(${expected.name})]`;
default:
return expected.name;
}
}
function getStartPos(expected: ExtendedAttribute): number {
switch (expected.orderType) {
case OrderType.StructuralDirective:
return expected.sourceSpan.start.offset - 1;
default:
return expected.sourceSpan.start.offset;
}
}
function getEndPos(expected: ExtendedAttribute): number {
switch (expected.orderType) {
case OrderType.StructuralDirective:
return expected.sourceSpan.end.offset + 1;
default:
return expected.sourceSpan.end.offset;
}
}