Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Expand the template-vars eslint rule to handle local methods #146

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 72 additions & 3 deletions packages/@glimmerx/eslint-plugin/lib/rules/template-vars.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,56 @@
const { getTemplateLocals } = require('@glimmer/syntax');
const { getTemplateLocals, preprocess, traverse } = require('@glimmer/syntax');

/**
* Adds tokens to the tokensSet if they're a path prefixed with `this.`
*/

function addTokens(tokensSet, node) {
if (node.type === 'PathExpression') {
if (node.this === true) {
// this will only look at the first level of methods on this, with no handling for (properties/methods) of methods
const topLevelMaybeToken = node.parts[0];

if (tokensSet.has(topLevelMaybeToken) === false) {
tokensSet.add(topLevelMaybeToken);
}
}
}
}

/**
* Parses and traverses a given handlebars html template to extract all references to local methods via `this.myMethod`
*/

function getThisTemplateLocals(html) {
const ast = preprocess(html);
const tokensSet = new Set();
traverse(ast, {
ElementNode(node) {
addTokens(tokensSet, node);
},

PathExpression(node) {
addTokens(tokensSet, node);
},
});
let tokens = [];
tokensSet.forEach((s) => tokens.push(s));

return tokens;
}

module.exports = {
docs: {
description:
'Components / Helpers referenced in hbs template literals should not trigger no-unused-vars failures, but should trigger no-undef if they are not defined propery',
'Components / Helpers referenced in hbs template literals should not trigger no-unused-vars failures, but should trigger template-vars if they are not defined propery',
category: 'Variables',
recommended: true,
},
meta: {
messages: {
undefToken: 'Token {{ token }} is used in an hbs tagged template literal, but is not defined',
undefLocalMethod:
'Local Token {{ token }} is used in an hbs tagged template literal, but is not defined',
},
// example: '@glimmerx/glimmerx/template-vars': [2, 'unused-only', { nativeTokens: ['anImplicitToken'] }]
schema: [
Expand Down Expand Up @@ -41,7 +82,8 @@ module.exports = {

const [mode = 'all', configOpts] = context.options;
let nativeTokens = (configOpts && configOpts.nativeTokens) || [];

let localUsedVars = [];
let localDefinedVars = [];
return {
ImportSpecifier(node) {
if (isGlimmerSfc || node.parent.source.value !== '@glimmerx/component') {
Expand All @@ -62,6 +104,8 @@ module.exports = {
const templateString = templateElementNode.value.raw;

const templateScopeTokens = getTemplateLocals(templateString);
localUsedVars = localUsedVars.concat(getThisTemplateLocals(templateString));

templateScopeTokens.forEach((token) => {
const isTokenPresent = context.markVariableAsUsed(token);
if (!isTokenPresent && !nativeTokens.includes(token) && mode === 'all') {
Expand All @@ -75,6 +119,31 @@ module.exports = {
}
});
},
MethodDefinition(node) {
localDefinedVars.push(node.key.name);
},
// needs to handle services
ClassProperty(node) {
localDefinedVars.push(node.key.name);
},
'ClassBody:exit'(node) {
let localUndefinedMethods = localUsedVars.filter(
(method) => !localDefinedVars.includes(method)
);
localUndefinedMethods.forEach((token) => {
context.report({
data: {
token,
},
messageId: 'undefLocalMethod',
node: node,
});
});
localUsedVars = [];
localDefinedVars = [];

//TODO: this assumes 1 class body, and cannot handle nested classes
},
};
},
};
80 changes: 77 additions & 3 deletions packages/@glimmerx/eslint-plugin/test/lib/rules/template-vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ describe('no-unused-vars', function () {
import { hbs as notHbs } from '@glimmerx/component';
import myHelper from './myHelper';
export default class Component {
static template = hbs\`I am using {{myHelper}} here, but I forgot to import hbs,
and also forgot to tag this template literal with hbs.\`;
static template = hbs\`I am using {{myHelper}} here, but I imported hbs under a different local name,
and tagged this template literal with hbs rather than its local name.\`;
method() {
return false;
}
Expand Down Expand Up @@ -277,13 +277,47 @@ ruleTester.run('template-vars', rule, {
`,
options: ['unused-only'],
},
{
code: `
import { hbs } from '@glimmerx/component';
export default class Component {
@service myService;
static template = hbs\`I am using {{this.foo1}},{{this.bar1}}, {{this.count1}}, {{this.myService}} here, and I've defined all locally.\`;

get foo1() {
return 1;
}

bar1 = 1;
@tracked count1 = 0;
}
`,
options: ['unused-only'],
},
{
code: `
class MyComponent extends Component {
static template = hbs\`
<button {{on "click" this.incrementCounter}}>Count: {{this.count}}</button>
\`;

@tracked count = 0;

@action
incrementCounter() {
this.count++;
}
}
`,
options: ['unused-only'],
},
],
invalid: [
{
code: `
import { hbs } from '@glimmerx/component';
export default class Component {
static template = hbs\`I am using {{myHelper}} here, but I forgot to tag this template literal with hbs.\`;
static template = hbs\`I am using {{myHelper}} here, but I forgot to import myHelper.\`;
method() {
return false;
}
Expand All @@ -297,5 +331,45 @@ ruleTester.run('template-vars', rule, {
],
options: ['all'],
},
{
code: `
import { hbs } from '@glimmerx/component';
export default class Component {
static template = hbs\`I am using {{this.myHelper}} here, but I forgot to define myHelper.\`;
method() {
return false;
}
test = true;
}
`,
errors: [
{
messageId: 'undefLocalMethod',
},
],
options: ['all'],
},
{
code: `
import { hbs } from '@glimmerx/component';
import foo3 from './foo3';
export default class Component {
static template = hbs\`I am using {{this.foo1.bar}} and {{this.foo3}} here, but I forgot to define foo3 even though I imported a different foo3.\`;

get foo1() {
return 1;
}

get foo2() {
return 2;
}
}
`,
errors: [
{
messageId: 'undefLocalMethod',
},
],
},
],
});