eslint-plugin-styled-component-jsx-attributes
Version:
A simple plugin for enforcing the use of the id attribute on styled components.
74 lines (62 loc) • 2.83 kB
JavaScript
var mergeStyledAttrsWithNodeAttrs = require('../mergeStyledAttrsWithNodeAttrs');
var getAsProp = require('../getAsProp');
var _require = require('util'),
inspect = _require.inspect;
module.exports = function (context, styledComponents, rule, name) {
return {
JSXOpeningElement: function JSXOpeningElement(node) {
var func = function func(inspectee) {
return name.includes('') && context.report(node, inspect(inspectee || node));
};
try {
var elementName = node.name.name;
if (!elementName && node.name.type === 'JSXMemberExpression') {
elementName = "".concat(node.name.object.name, ".").concat(node.name.property.name);
}
var styledComponent = styledComponents[elementName];
if (styledComponent) {
var tag = styledComponent.tag,
attrs = styledComponent.attrs;
var originalNodeAttr = node.attributes;
var originalNodeName = node.name;
var allAttrs = mergeStyledAttrsWithNodeAttrs(attrs, originalNodeAttr);
var asProp = getAsProp(allAttrs);
allAttrs.forEach(function (atr) {
var originalAtrLoc = atr.loc;
var originalParent = atr.parent; // need to save the attrs of both the atr parent and the actual node depending on which one we use as the parent so we can reassign them back after
var originalAtrParentAttributes = atr.parent && atr.parent.attributes;
var originalNodeAttributes = node.attributes;
var nodeNameProperties;
try {
if (!atr.parent) {
atr.parent = node;
nodeNameProperties = originalNodeName;
} else {
nodeNameProperties = originalParent.name;
}
atr.loc = node.loc; // Convert JSXMemberExpression to JSXIdentifier, so it'll be properly handled by eslint-plugin-jsx-id-attribute-enforcement plugin
atr.parent.name = {
type: 'JSXIdentifier',
name: asProp || tag,
start: nodeNameProperties.start,
end: nodeNameProperties.end,
loc: nodeNameProperties.loc,
range: nodeNameProperties.range,
parent: nodeNameProperties.parent
};
atr.parent.attributes = allAttrs;
rule.create(context).JSXAttribute(atr, func);
} finally {
atr.loc = originalAtrLoc;
atr.parent = originalParent;
if (originalAtrParentAttributes) atr.parent.attributes = originalAtrParentAttributes;
node.name = originalNodeName;
node.attributes = originalNodeAttributes;
}
});
}
} catch (_unused) {}
}
};
};
;