forked from ember-cli/eslint-plugin-ember
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-no-action-modifiers.js
More file actions
97 lines (90 loc) · 3.04 KB
/
template-no-action-modifiers.js
File metadata and controls
97 lines (90 loc) · 3.04 KB
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
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'disallow usage of {{action}} modifiers',
category: 'Best Practices',
url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/template-no-action-modifiers.md',
},
fixable: 'code',
schema: [
{
oneOf: [
{
type: 'array',
items: { type: 'string' },
uniqueItems: true,
},
{
type: 'object',
properties: {
allowlist: {
type: 'array',
items: { type: 'string' },
uniqueItems: true,
},
},
additionalProperties: false,
},
],
},
],
messages: {
noActionModifier: 'Do not use action modifiers. Use on modifier with a function instead.',
},
},
create(context) {
const firstOption = context.options[0];
const allowlist = Array.isArray(firstOption) ? firstOption : firstOption?.allowlist || [];
const sourceCode = context.sourceCode;
function checkForActionModifier(node) {
if (
node.path &&
node.path.type === 'GlimmerPathExpression' &&
node.path.original === 'action' &&
node.path.head?.type !== 'AtHead' &&
node.path.head?.type !== 'ThisHead'
) {
// Only offer autofix when the first param is a path expression
// and there are no hash pairs (e.g. on="submit") which would be left behind
const maybePath = node.params?.[0];
const hasHashPairs = node.hash?.pairs?.length > 0;
const canFix = maybePath && maybePath.type === 'GlimmerPathExpression' && !hasHashPairs;
context.report({
node,
messageId: 'noActionModifier',
fix: canFix
? (fixer) => {
const args = node.params.slice(1);
const pathText = sourceCode.getText(maybePath);
let replacement;
if (args.length === 0) {
// {{action this.handleClick}} → {{on "click" this.handleClick}}
replacement = `on "click" ${pathText}`;
} else {
// {{action this.handleClick "arg"}} → {{on "click" (fn this.handleClick "arg")}}
const argsText = args.map((a) => sourceCode.getText(a)).join(' ');
replacement = `on "click" (fn ${pathText} ${argsText})`;
}
const lastParam = node.params.at(-1);
return fixer.replaceTextRange(
[node.path.range[0], lastParam.range[1]],
replacement
);
}
: null,
});
}
}
return {
GlimmerElementModifierStatement(node) {
const parent = node.parent;
if (parent && parent.type === 'GlimmerElementNode' && allowlist.includes(parent.tag)) {
return;
}
checkForActionModifier(node);
},
};
},
};