Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created July 23, 2018 22:30
Show Gist options
  • Save souporserious/4cc9b705a8dd9d5d837bba5459589dac to your computer and use it in GitHub Desktop.
Save souporserious/4cc9b705a8dd9d5d837bba5459589dac to your computer and use it in GitHub Desktop.
import React from 'react'
import PropTypes from 'prop-types'
import Box from '../Box'
import { cloneChildren, joinChildren } from '../utils'
const BASELINE = 'baseline'
const CENTER = 'center'
const END = 'end'
const FILL = 'fill'
const HORIZONTAL = 'horizontal'
const SPACE_EVENLY = 'space-evenly'
const SPACE_BETWEEN = 'space-between'
const START = 'start'
const STRETCH = 'stretch'
const VERTICAL = 'vertical'
function StackView({
inline,
alignment,
axis = VERTICAL,
children,
distribution,
spacing,
...props
}) {
const isSpacingNumber = typeof spacing === 'number'
const childrenToRender = cloneChildren(children, (child, { lastChild }) => {
const childProps = {}
if (distribution === FILL) {
if (child.props.grow === undefined) {
childProps.grow = 1
}
if (child.props.shrink === undefined) {
childProps.shrink = 0
}
if (child.props.basis === undefined) {
childProps.basis = 0
}
}
if (isSpacingNumber && !lastChild) {
if (axis === HORIZONTAL) {
if (child.props.marginRight === undefined) {
childProps.marginRight = spacing
}
} else {
if (child.props.marginBottom === undefined) {
childProps.marginBottom = spacing
}
}
}
return childProps
})
return (
<Box
display={inline ? 'inline-flex' : 'flex'}
direction={axis === HORIZONTAL ? 'row' : 'column'}
alignItems={alignment}
justifyContent={distribution}
{...props}
>
{distribution === SPACE_EVENLY ? <Box /> : null}
{isSpacingNumber || spacing === undefined
? childrenToRender
: joinChildren(childrenToRender, spacing)}
{distribution === SPACE_EVENLY ? <Box /> : null}
</Box>
)
}
StackView.propTypes = {
alignment: PropTypes.oneOf([BASELINE, CENTER, END, START, STRETCH]),
axis: PropTypes.oneOf([HORIZONTAL, VERTICAL]),
distribution: PropTypes.oneOf([
CENTER,
END,
FILL,
SPACE_BETWEEN,
SPACE_EVENLY,
START,
]),
spacing: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.element,
]),
}
StackView.BASELINE = BASELINE
StackView.CENTER = CENTER
StackView.END = END
StackView.FILL = FILL
StackView.HORIZONTAL = HORIZONTAL
StackView.SPACE_BETWEEN = SPACE_BETWEEN
StackView.SPACE_EVENLY = SPACE_EVENLY
StackView.START = START
StackView.STRETCH = STRETCH
StackView.VERTICAL = VERTICAL
export default StackView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment