eslint-plugin-styled-components-a11y
Version:
This plugin adds the ability to lint styled components according to the rules outlined in eslint-plugin-jsx-a11y.
67 lines (66 loc) • 2.96 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-a11y 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;
// if we haven't discovered what type of tag the component is based off, bail
if (!(asProp || tag)) return;
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) {}
}
};
};