Last active
February 5, 2018 16:43
-
-
Save brendanmoore/4ad3751c510f3c41ea5085c5ac217bd6 to your computer and use it in GitHub Desktop.
Convert JSX on{EventName} from Logical Expression to Ternary shorthand
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
/** | |
* Converts: | |
* From: <button onClick={someIdentifier && this.handleClick} /> | |
* To: <button onClick={someIdentifier ? this.handleClick : undefined} /> | |
*/ | |
export default function transformer(file, api) { | |
const j = api.jscodeshift; | |
const interactiveEventTypeNames = [ | |
'blur', | |
'cancel', | |
'click', | |
'close', | |
'contextMenu', | |
'copy', | |
'cut', | |
'doubleClick', | |
'dragEnd', | |
'dragStart', | |
'drop', | |
'focus', | |
'input', | |
'invalid', | |
'keyDown', | |
'keyPress', | |
'keyUp', | |
'mouseDown', | |
'mouseUp', | |
'paste', | |
'pause', | |
'play', | |
'rateChange', | |
'reset', | |
'seeked', | |
'submit', | |
'touchCancel', | |
'touchEnd', | |
'touchStart', | |
'volumeChange', | |
]; | |
const nonInteractiveEventTypeNames = [ | |
'abort', | |
'animationEnd', | |
'animationIteration', | |
'animationStart', | |
'canPlay', | |
'canPlayThrough', | |
'drag', | |
'dragEnter', | |
'dragExit', | |
'dragLeave', | |
'dragOver', | |
'durationChange', | |
'emptied', | |
'encrypted', | |
'ended', | |
'error', | |
'load', | |
'loadedData', | |
'loadedMetadata', | |
'loadStart', | |
'mouseMove', | |
'mouseOut', | |
'mouseOver', | |
'playing', | |
'progress', | |
'scroll', | |
'seeking', | |
'stalled', | |
'suspend', | |
'timeUpdate', | |
'toggle', | |
'touchMove', | |
'transitionEnd', | |
'waiting', | |
'wheel', | |
]; | |
const upperCaseFirst = str => str.charAt(0).toUpperCase() + str.slice(1); | |
const methods = [ | |
...interactiveEventTypeNames, | |
...nonInteractiveEventTypeNames | |
].map(evtName => `on${upperCaseFirst(evtName)}`); | |
return j(file.source) | |
.find(j.JSXAttribute, { name: { type: "JSXIdentifier" } }) | |
.filter(p => methods.includes(p.get().value.name.name)) | |
.forEach(p => { | |
const exp = j(p).find(j.JSXExpressionContainer); | |
j(p).find(j.LogicalExpression).forEach(p => { | |
const left = p.node.left; | |
const right = p.node.right; | |
const next = j.template.statement`{${left} ? ${right} : undefined}`; | |
j(p.parent).replaceWith(next); | |
}) | |
}) | |
.toSource(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment