Skip to content

Commit

Permalink
feat(util-helpers): add handle responsive styles for use in box and card
Browse files Browse the repository at this point in the history
  • Loading branch information
meeschka authored and jraff committed Sep 4, 2020
1 parent e9a75f3 commit f3ac104
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
29 changes: 28 additions & 1 deletion packages/helpers/__tests__/generateResponsiveStyles.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { prepareArray, generateStyles } from '../generateResponsiveStyles'
import { prepareArray, generateStyles, handleResponsiveStyles } from '../generateResponsiveStyles'

describe('generateResponsiveStyles', () => {
describe('prepareArray', () => {
Expand Down Expand Up @@ -346,4 +346,31 @@ describe('generateResponsiveStyles', () => {
})
})
})

describe('handleResponsiveStyle', () => {
const props = {
vertical: { xs: 4, md: 8 },
}
const styleFn = ({ vertical }) => {
if (vertical === undefined) {
return undefined
}

return { paddingTop: vertical, paddingBottom: vertical }
}

it('works', () => {
const styles = handleResponsiveStyles(props, styleFn)
expect(styles).toEqual({
'@media (max-width: 767px)': {
paddingTop: 4,
paddingBottom: 4,
},
'@media (min-width: 768px)': {
paddingTop: 8,
paddingBottom: 8,
},
})
})
})
})
28 changes: 28 additions & 0 deletions packages/helpers/generateResponsiveStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,37 @@ export const generateStyles = (breakpoints, style) => {
return styles
}

const handleBoundaryCrossing = (acc, curr) => {
if (
isMobileBreakpoint(curr.from) &&
((curr.until !== 'md' && isDesktopBreakpoint(curr.until)) || typeof curr.until === 'undefined')
) {
const props = Object.keys(curr.props).filter(
prop => typeof curr.props[prop] === 'number' && curr.props[prop] > 3
)
if (props.length !== 0) {
const mobileBreakpoint = { ...curr, props: curr.props }
const desktopBreakpoint = { ...curr, props: curr.props }

mobileBreakpoint.until = 'md'
desktopBreakpoint.from = 'md'

return acc.concat([mobileBreakpoint, desktopBreakpoint])
}
}
return acc.concat([curr])
}

export const generateResponsiveStyles = (props, styleFn) => {
const breakpoints = prepareArray(props)
return generateStyles(breakpoints, styleFn)
}

export const handleResponsiveStyles = (props, styleFn) => {
const breakpoints = prepareArray(props)
.filter(bp => Object.keys(bp.props).length > 0)
.reduce(handleBoundaryCrossing, [])
return generateStyles(breakpoints, styleFn)
}

export default generateResponsiveStyles
1 change: 1 addition & 0 deletions packages/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export {
default as generateResponsiveStyles,
prepareArray,
generateStyles,
handleResponsiveStyles,
} from './generateResponsiveStyles'

0 comments on commit f3ac104

Please sign in to comment.