Skip to content

Commit

Permalink
feat: Add codemod to use the breakpoints hook
Browse files Browse the repository at this point in the history
  • Loading branch information
ptbrowne committed May 11, 2020
1 parent 9bc2885 commit 511b457
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
16 changes: 16 additions & 0 deletions codemods/use-breakpoints-hook/example-after.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React from 'react'
import { useBreakpoints } from 'cozy-ui/transpiled/react'

const MobileComponent = () => <>Mobile</>
const DesktopComponent = () => <>Desktop</>

const Component = () => {
const { isMobile, isDesktop } = useBreakpoints()
return isMobile ? (
<MobileComponent />
) : isDesktop ? (
<DesktopComponent />
) : null
}

export default otherHoc(Component)
19 changes: 19 additions & 0 deletions codemods/use-breakpoints-hook/example-before.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react'
import compose from 'lodash/flowRight'
import { withBreakpoints } from 'cozy-ui/transpiled/react'

const MobileComponent = () => <>Mobile</>
const DesktopComponent = () => <>Desktop</>

const Component = ({ breakpoints: { isMobile, isDesktop } }) => {
return isMobile ? (
<MobileComponent />
) : isDesktop ? (
<DesktopComponent />
) : null
}

export default compose(
withBreakpoints(),
otherHoc
)(Component)
49 changes: 49 additions & 0 deletions codemods/use-breakpoints-hook/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { hocReplacer } from '@cozy/codemods'

const isBreakpointProp = prop => {
return prop.key && prop.key.name === 'breakpoints'
}

const findBreakpointsProp = objPattern => {
if (!objPattern) {
return
}
if (objPattern.type !== 'ObjectPattern') {
return
}

return objPattern.properties
? objPattern.properties.filter(isBreakpointProp).map(prop => prop)
: []
}

export default function transformer(file, api) {
const j = api.jscodeshift
const root = j(file.source)

const replaceBreakpointsHOC = hocReplacer({
propsFilter: isBreakpointProp,
propsFinder: findBreakpointsProp,
hookUsage: foundProps => {
return `const ${foundProps
.map(p => j(p.value).toSource())
.join(', ')} = useBreakpoints()`
},
hocName: 'withBreakpoints',
j,
importOptions: {
filter: x => {
return (
x.source.value == 'cozy-ui/transpiled/react' ||
x.source.value == 'cozy-ui/react'
)
},
specifiers: {
useBreakpoints: true
},
package: 'cozy-ui/transpiled/react'
}
})

return replaceBreakpointsHOC(root)
}

0 comments on commit 511b457

Please sign in to comment.