Skip to content

Commit

Permalink
Improve JSX support
Browse files Browse the repository at this point in the history
Some JSX node types are hardcoded in childKeys to ensure correct property traversal
order. For example, this ensures that a JSXElement's children is traversed prior
to the closing element.
  • Loading branch information
danielstjules committed Mar 28, 2017
1 parent 04ff6e4 commit 119e32d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
18 changes: 14 additions & 4 deletions lib/nodeUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@ var stable = require('stable');

/**
* Cache for getChildren, holding the keys to traverse for a given Node type.
* Some JSX node types are hardcoded to ensure correct property traversal order.
* For example, this ensures that a JSXElement's children is traversed prior
* to the closing element.
*/
var childKeys = {};
var childKeys = {
JSXElement: ['openingElement', 'extra', 'children', 'closingElement'],
JSXOpeningElement: ['name', 'attributes'],
JSXAttribute: ['name', 'value'],
};

class NodeUtils {
/**
Expand Down Expand Up @@ -93,7 +100,7 @@ class NodeUtils {

if (!childKeys[node.type]) {
childKeys[node.type] = Object.keys(node).filter((key) => {
return typeof node[key] === 'object';
return key !== 'loc' && typeof node[key] === 'object';
});
}

Expand Down Expand Up @@ -239,9 +246,12 @@ class NodeUtils {
* @returns {boolean}
*/
static literalsMatch(nodes) {
var isLiteral = (node) => {
return node.type.includes('Literal') || node.type === 'JSXText';
}

return nodes[0] && nodes.every(node => {
return node && (!node.type.includes('Literal') ||
node.value === nodes[0].value);
return node && (!isLiteral(node) || node.value === nodes[0].value);
});
}
}
Expand Down
9 changes: 9 additions & 0 deletions spec/nodeUtilsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,15 @@ describe('NodeUtils', function() {
expect(res).to.be(false);
});

it('treats JSXText as a literal', function() {
var res = NodeUtils.literalsMatch([
{type: 'JSXText', value: 'a'},
{type: 'JSXText', value: 'a'},
{type: 'JSXText', value: 'b'}
]);
expect(res).to.be(false);
});

it('ignores the values of nodes which are not literals', function() {
var res = NodeUtils.literalsMatch([
{type: 'Foo', value: 'a'},
Expand Down

0 comments on commit 119e32d

Please sign in to comment.