Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Created August 22, 2017 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvaughn/9124baade46f9605ccb639928d0cf3f0 to your computer and use it in GitHub Desktop.
Save bvaughn/9124baade46f9605ccb639928d0cf3f0 to your computer and use it in GitHub Desktop.
Auto-generate css labels for Glamor components
const hasLabelProperty = path =>
path.node.value.expression.properties.find(
property => property.key.name === "label"
);
const isGlamorAttribute = path => {
return path.node.name.name === "css";
};
const getParentComponentName = path => {
let parentPath = path.parentPath;
while (parentPath) {
if (
parentPath.node.type === "FunctionDeclaration" ||
parentPath.node.type === "ClassDeclaration"
) {
return parentPath.node.id.name;
} else if (parentPath.node.type === "ArrowFunctionExpression") {
return parentPath.parentPath.node.id.name;
}
parentPath = parentPath.parentPath;
}
};
const tagNameMap = {};
export default function(babel) {
const { types } = babel;
return {
visitor: {
JSXAttribute(path, state) {
if (isGlamorAttribute(path)) {
if (hasLabelProperty(path)) {
return;
}
const tag = path.parent.name.name;
const componentName = getParentComponentName(path);
if (!componentName) {
return;
}
if (!tagNameMap.hasOwnProperty(componentName)) {
tagNameMap[componentName] = {};
}
let tagSuffix = "";
if (!tagNameMap[componentName].hasOwnProperty(tag)) {
tagNameMap[componentName][tag] = 0;
} else {
tagNameMap[componentName][tag]++;
tagSuffix = `-${tagNameMap[componentName][tag]}`;
}
const label = `${componentName}-${tag}${tagSuffix}`;
path.node.value.expression.properties.push(
types.ObjectProperty(
types.Identifier("label"),
types.StringLiteral(label)
)
);
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment