Skip to content

Commit

Permalink
build: add linting for classList usage
Browse files Browse the repository at this point in the history
Once in a while we hit an issue because we use some of the `classList` methods in a way that isn't supported in all browsers (e.g. passing multiple parameters to `add` in angular#17378). These changes add a simple lint rule to catch these cases earlier.
  • Loading branch information
crisbeto committed Oct 13, 2019
1 parent 14c4dba commit 721ad03
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tools/tslint-rules/classListSignaturesRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import * as ts from 'typescript';
import * as Lint from 'tslint';

/**
* Rule that catches cases where `classList` is used in a way
* that won't work in all browsers that we support.
*/
export class Rule extends Lint.Rules.TypedRule {
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions(), program));
}
}

class Walker extends Lint.ProgramAwareRuleWalker {
visitPropertyAccessExpression(propertyAccess: ts.PropertyAccessExpression) {
const parent = propertyAccess.parent;

// We only care about property accesses inside of calls.
if (!ts.isCallExpression(parent)) {
return;
}

// We only care about these method names.
const name = propertyAccess.name.text;
if (name !== 'add' && name !== 'remove' && name !== 'toggle' && name !== 'replace') {
return;
}

const symbol = this.getTypeChecker().getTypeAtLocation(propertyAccess.expression).symbol;

if (symbol && symbol.name === 'DOMTokenList') {
const args = parent.arguments;

if (name === 'replace') {
this.addFailureAtNode(propertyAccess,
'This method is not supported in iOS Safari. Use `add` and `remove` instead,');
} else if (args.length > 1 || (args.length === 1 && ts.isSpreadElement(args[0]))) {
this.addFailureAtNode(propertyAccess,
'Passing in multiple arguments into this method is not supported in some browsers. ' +
'Use the single argument signature instead.');
}
}

super.visitPropertyAccessExpression(propertyAccess);
}
}
1 change: 1 addition & 0 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"rxjs-imports": true,
"require-breaking-change-version": true,
"static-query": true,
"class-list-signatures": true,
"no-host-decorator-in-concrete": [
true,
"HostBinding",
Expand Down

0 comments on commit 721ad03

Please sign in to comment.