@eureca/eureca-ui
Version:
UI component library of Eureca's user and admin apps
124 lines (111 loc) • 3.09 kB
JavaScript
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Typography, Box, ClickAwayListener, Popper } from '@material-ui/core';
import { ChromePicker } from 'react-color';
import { FaTimesCircle } from 'react-icons/fa';
import { Flex } from '../Flex';
import { colors } from '../../theme/colors';
const styles = {
dialog: {
position: 'absolute',
borderRadius: 4,
zIndex: 500,
},
};
const Colorpicker = ({
label = '',
initialValue = '#FFF',
onChange = () => {},
helperText,
error,
}) => {
const [colorValue, setColorValue] = useState(initialValue);
const [anchorEl, setAnchorEl] = React.useState(null);
function toggleColorPicker(event) {
setAnchorEl(anchorEl ? null : event.currentTarget);
}
function handleClickAway() {
setAnchorEl(null);
}
function handleChange(color) {
setColorValue(color.hex);
if (onChange) {
onChange(color.hex);
}
}
function setDefault(event) {
event.stopPropagation();
handleChange({ hex: colors.white });
}
return (
<Box>
<Flex directionRow alignCenter>
<Box mr={1}>
<Typography variant="body1" style={{ color: error ? colors.error1 : colors.gray2 }}>
{label}
</Typography>
</Box>
<Flex
directionRow
justifySpaceBetween
alignCenter
cursorPointer
px={2}
borderRadius={4}
minWidth={134}
border={`1px solid ${error ? colors.error1 : colors.gray3}`}
onClick={toggleColorPicker}
>
<Box
overflow="hidden"
borderRadius="50%"
bgcolor={colorValue ?? colors.white}
width={16}
height={16}
border={`1px solid ${colors.gray4}`}
/>
<Box p={1}>
<Typography variant="body2" style={{ color: colors.gray2 }}>
{colorValue}
</Typography>
</Box>
<Flex alignCenter justifyCenter cursorPointer onClick={e => setDefault(e)}>
<FaTimesCircle color={colors.gray3} size={20} />
</Flex>
<Popper
open={Boolean(anchorEl)}
anchorEl={anchorEl}
transition
onClick={e => e.stopPropagation()}
style={styles.dialog}
>
<ClickAwayListener onClickAway={handleClickAway}>
<ChromePicker
color={colorValue}
disableAlpha
onChange={color => handleChange(color)}
/>
</ClickAwayListener>
</Popper>
</Flex>
</Flex>
<Box mt="3px" ml="14px">
<Typography
variant="body2"
style={{
color: error ? colors.error1 : colors.gray3,
lineHeight: 1.66,
}}
>
{helperText}
</Typography>
</Box>
</Box>
);
};
Colorpicker.propTypes = {
label: PropTypes.string,
initialValue: PropTypes.string,
onChange: PropTypes.func,
};
export { Colorpicker };