This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
78 lines (71 loc) · 3.61 KB
/
index.js
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
/**
* @fileoverview Rule to check ChangeDetectionStrategy
* @author Eduard Gorte
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const COMMA = ',';
const EMPTY = '';
const CHANGE_DETECTION_KEY = 'changeDetection';
const CHANGE_DETECTION_STRATEGY = 'ChangeDetectionStrategy';
const ON_PUSH = 'OnPush';
const CHANGE_DETECTION_STRATEGY_ON_PUSH = CHANGE_DETECTION_STRATEGY + '.' + ON_PUSH;
const SELECTOR_KEY = 'selector';
const SINGLE_SPACE = ' ';
const FALLBACK_INDENT = 2;
const NEWLINE = '\n';
const rules = {
"on-push": {
meta: {
type: "suggestion",
docs: {
description: "check ChangeDetectionStrategy is OnPush",
category: "Possible Errors",
recommended: true,
},
fixable: "code",
schema: [] // no options
},
create: function (context) {
return {
CallExpression(node) {
if (node.callee.name === 'Component') {
const sourceCode = context.getSourceCode(node);
const configurationMetadata = sourceCode.getText(node);
const invalid = configurationMetadata.indexOf(CHANGE_DETECTION_STRATEGY_ON_PUSH) === -1;
if (invalid) {
context.report({
node: node.callee, // Component
message: `${node.callee.name} should have ${CHANGE_DETECTION_STRATEGY_ON_PUSH}`,
fix: function (fixer) {
const hasChangeDetectionKey = configurationMetadata.indexOf(CHANGE_DETECTION_KEY) !== -1;
// I don't know how to get child node, gonna get tokens instead
const tokens = sourceCode.getTokens(node.arguments[0]);
if (hasChangeDetectionKey) {
// Get index of enum property token separated the dot token
const targetTokenIndex = tokens.findIndex(x => x.value === CHANGE_DETECTION_STRATEGY) + 2;
return fixer.replaceText(tokens[targetTokenIndex], ON_PUSH);
} else {
const selectorToken = tokens.find((t) => t.value === SELECTOR_KEY);
const indent = selectorToken ? selectorToken.loc.start.column : FALLBACK_INDENT;
// We don't need two punctuator tokens `})`
const lastPropertyPunctuatorToken = tokens[tokens.length - 2];
// Check for the presence of a comma character to avoid unnecessary insertion
const hasComma = lastPropertyPunctuatorToken.value === COMMA;
// Insert code block as multiline string with indent
return fixer.insertTextAfter(lastPropertyPunctuatorToken, `${hasComma ? EMPTY : COMMA}${NEWLINE}${SINGLE_SPACE.repeat(indent)}${CHANGE_DETECTION_KEY}: ${CHANGE_DETECTION_STRATEGY_ON_PUSH}`);
}
}
});
}
}
}
};
}
}
};
module.exports = {
rules,
}