Skip to content

Commit

Permalink
Implement jsx-key rule (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
bolatovumar authored and adidahiya committed Aug 1, 2017
1 parent 7dac374 commit fdb14c4
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 0 deletions.
108 changes: 108 additions & 0 deletions src/rules/jsxKeyRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as Lint from "tslint";
import {
isArrayLiteralExpression,
isArrowFunction,
isBlock,
isCallExpression,
isFunctionExpression,
isJsxAttribute,
isJsxElement,
isJsxSelfClosingElement,
isParenthesizedExpression,
isPropertyAccessExpression,
isReturnStatement,
} from "tsutils";
import * as ts from "typescript";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "jsx-key",
description: Lint.Utils.dedent
`Warn if an element that likely requires a key prop — namely, \
one present in an array literal or an arrow function expression.`,
options: null,
optionsDescription: "",
optionExamples: ["true"],
type: "functionality",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING = 'Missing "key" prop for element.';

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}

function walk(ctx: Lint.WalkContext<void>): void {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if ((isJsxElement(node) || isJsxSelfClosingElement(node))
&& node.parent !== undefined
&& isArrayLiteralExpression(node.parent)) {
checkIteratorElement(node, ctx);
}

if (isPropertyAccessExpression(node) && node.name.text === "map") {
const mapFn = node.parent !== undefined && isCallExpression(node.parent)
? node.parent.arguments[0]
: undefined;

if (mapFn !== undefined && (isArrowFunction(mapFn) || isFunctionExpression(mapFn))) {
if (isJsxElement(mapFn.body) || isJsxSelfClosingElement(mapFn.body)) {
checkIteratorElement(mapFn.body, ctx);
} else if (isBlock(mapFn.body)) {
const returnStatement = getReturnStatement(mapFn.body.statements);

if (returnStatement !== undefined && returnStatement.expression !== undefined) {
if (isParenthesizedExpression(returnStatement.expression)) {
checkIteratorElement(returnStatement.expression.expression, ctx);
} else {
checkIteratorElement(returnStatement.expression, ctx);
}
}
}
}
}

return ts.forEachChild(node, cb);
});
}

function checkIteratorElement(node: ts.Node, ctx: Lint.WalkContext<void>) {
if (isJsxElement(node) && !hasKeyProp(node.openingElement.attributes)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}

if (isJsxSelfClosingElement(node) && !hasKeyProp(node.attributes)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}
}

function hasKeyProp(attributes: ts.JsxAttributes) {
return attributes.properties
.map((prop) => isJsxAttribute(prop) && prop.name.text === "key")
.indexOf(true) !== -1;
}

function getReturnStatement(body: ts.NodeArray<ts.Statement>) {
return body.filter((item) => isReturnStatement(item))[0] as ts.ReturnStatement | undefined;
}
49 changes: 49 additions & 0 deletions test/rules/jsx-key/test.tsx.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
fn()
[1, 2, 3].map(function () {})
<App />;
[<App key={0} />, <App key={1} />];
[1, 2, 3].map(function(x) { return <App key={x} /> });
[1, 2, 3].map(x => <App key={x} />);
[1, 2, 3].map(x => { return <App key={x} /> });
[1, 2, 3].foo(x => <App />);
var App = () => <div />;
[1, 2, 3].map(function(x) { return; });
foo(() => <div />)
[<App />];

[<App {...key} />];
~~~~~~~~~~~~~~~~ [0]

[<App key={0}/>, <App />];
~~~~~~~ [0]

[1, 2, 3].map(function(x) { return <App /> });
~~~~~~~ [0]

[3, 4, 5].map(x => <App />);
~~~~~~~ [0]

[6, 7, 8].map(x => { return <App /> });
~~~~~~~ [0]

function nestedRender() {
return (
<div>
{
[9, 10, 3].map(function (num) {
return (
<div key={num}>
{
[1, 2, 3].map(index => {
return <div />;
~~~~~~~ [0]
})
}
</div>
);
})
}
</div>
);
}
[0]: Missing "key" prop for element.
5 changes: 5 additions & 0 deletions test/rules/jsx-key/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"jsx-key": true
}
}

0 comments on commit fdb14c4

Please sign in to comment.