Repository URL to install this package:
|
Version:
8.1.0-rc.5 ▾
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Button, ButtonLabel, IconButton } from '../Button';
import InputFeedback from './InputFeedback';
import SyncIcon from '../../visuals/Icon/svg/d_sync_enable.svg';
class ColorPicker extends Component {
static propTypes = {
/** Provides the default background color */
defaultColor: PropTypes.string.isRequired,
/** Provides the background color that has been previously saved */
color: PropTypes.string,
/** Provides a function that will be called after the color state changes and passes the new color as an argument. */
onColorChange: PropTypes.func.isRequired,
onBlur: PropTypes.func,
label: PropTypes.string,
valid: PropTypes.bool,
errorMessage: PropTypes.string,
disabled: PropTypes.bool,
};
static defaultProps = {
color: null,
label: null,
valid: true,
errorMessage: '',
disabled: false,
onBlur: () => {},
};
constructor(props) {
super(props);
this.state = {
currentColor: this.props.color || this.props.defaultColor,
isColorInputSupported: this.isColorInputSupported(),
};
}
onButtonClick = () => {
this.input.click();
};
onInternalChange = e => {
const currentColor = e.target.value;
this.setState({ currentColor });
this.props.onColorChange(currentColor);
};
onReset = () => {
const currentColor = this.props.defaultColor;
this.setState({ currentColor });
this.props.onColorChange(currentColor);
};
setInputRef = node => {
this.input = node;
};
isColorInputSupported = () => {
const input = document.createElement('input');
input.setAttribute('type', 'color');
return input.type !== 'text';
};
render() {
const { currentColor, isColorInputSupported } = this.state;
const { label, defaultColor, valid, errorMessage, onBlur, disabled } = this.props;
const shouldShowResetButton = defaultColor !== currentColor;
const className = classnames(
{ 'ColorPicker-input Input-field': !isColorInputSupported },
{ 'ColorPicker-input--hideInput': isColorInputSupported },
{ 'ColorPicker-input--invalid': !valid }
);
return (
<div className="ColorPicker">
{isColorInputSupported && (
<Button variant="whiteWithBorder" type="button" onClick={this.onButtonClick} disabled={disabled}>
<div
className="ColorPicker-buttonIcon Button-icon"
style={{
background: currentColor,
}}
/>
<ButtonLabel>{label}</ButtonLabel>
</Button>
)}
<input
className={className}
type="color"
value={currentColor}
ref={this.setInputRef}
onChange={this.onInternalChange}
onBlur={onBlur}
disabled={disabled}
/>
{shouldShowResetButton &&
!disabled && (
<IconButton
className="ColorPicker-resetIcon"
type="button"
variant="whiteWithBorder"
icon={SyncIcon}
semantic="Reset color"
dimension="small"
onClick={this.onReset}
/>
)}
{!valid && errorMessage && <InputFeedback type="error">{errorMessage}</InputFeedback>}
</div>
);
}
}
export default ColorPicker;