Created
August 22, 2017 04:55
-
-
Save bvaughn/9124baade46f9605ccb639928d0cf3f0 to your computer and use it in GitHub Desktop.
Auto-generate css labels for Glamor components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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