@bigfishtv/cockpit
Version:
72 lines (65 loc) • 2.36 kB
JavaScript
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { SketchPicker } from 'react-color'
import classnames from 'classnames'
/**
* Displays a color block that can be clicked to modify color using 'react-color' color picker
*/
export default class Color extends Component {
static propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
/** xsmall, small, medium, large, xlarge, appends to className. Default is medium */
size: PropTypes.string,
/** Style to apply to wrapper div */
style: PropTypes.object,
/** Show / hide alpha slider. Should typically be disabled when used as a Field input */
disableAlpha: PropTypes.bool,
/** Reference to a different react-color component, is SketchPicker by default. */
Component: PropTypes.any,
/** Transformation function that provides value to onChange. Returns HEX by default, options include: hex, hsl {h,s,l,a}, hsv {h,s,v,a}, rgb {r,g,b,a} */
transformValue: PropTypes.func,
/** Returns value supplied by transformValue prop */
onChange: PropTypes.func,
/** props to be spread over Component, e.g. presetColors[] */
componentProps: PropTypes.object,
}
static defaultProps = {
size: null,
value: '#FFFFFF',
style: {},
disableAlpha: true,
Component: SketchPicker,
onChange: () => console.warn('no onChange prop provided for Color'),
transformValue: value => value.hex,
componentProps: {},
}
constructor(props) {
super(props)
this.state = { displayColorPicker: false }
}
toggleDisplay = () => {
this.setState({ displayColorPicker: !this.state.displayColorPicker })
}
render() {
const { displayColorPicker } = this.state
const { size, value, style, disableAlpha, transformValue, componentProps } = this.props
return (
<div
className={classnames('color', size)}
style={{ ...style, backgroundColor: value }}
onClick={() => !displayColorPicker && this.toggleDisplay()}>
{this.state.displayColorPicker && (
<div className="color-picker-wrapper">
<div className="color-picker-cover" onClick={this.toggleDisplay} />
<SketchPicker
{...componentProps}
disableAlpha={disableAlpha}
color={value || 'rgba(255,255,255,0)'}
onChangeComplete={value => this.props.onChange(transformValue(value))}
/>
</div>
)}
</div>
)
}
}