/* Dependencies */ import React, { useState, useEffect } from 'react' import { StyleSheet, Text, View } from 'react-native' /* Libraries */ import { exceptThis } from '@hproinformatica/functions' import { TextInput, IconButton, useTheme, Surface } from 'react-native-paper' /* Types */ type Props = { title: string color: string } const Color = ({ title, color }: Props) => { /* Styles */ const { colors } = useTheme() const styles = StyleSheet.create({ colorInput: { height: 50, marginRight: 10, width: 80 }, container: { backgroundColor: colors.background, borderRadius: 15, display: 'flex', elevation: 4, marginBottom: 20, padding: 10 }, title: { color: colors.text, fontSize: 20, fontWeight: 'bold', marginBottom: 5, marginLeft: 5 } }) /* States */ const [red, setRed] = useState('') const [green, setGreen] = useState('') const [blue, setBlue] = useState('') const [hex, setHex] = useState('') const [col, setCol] = useState('') const [display, setDisplay] = useState('HEX') /* Functions */ // TODO function rgbToHex(r: number, g: number, b: number) { return '#' + ((1 << 24) + (r << 16) + (g << 8) + b) .toString(16) .slice(1) } function hexToRgb(hex: string) { let result = new RegExp(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex) return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null } const handleRgbToHex = () => { setHex(rgbToHex(parseInt(red), parseInt(green), parseInt(blue)).replace('#', '')) setDisplay('HEX') } const handleHexToRgb = () => { let cAux = '' if (hex.length !== 6) { if (hex.length === 3) { cAux = `${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}` } else if (hex.length < 3) { cAux = `ffffff` } else if (hex.length > 3) { cAux = `${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}` } } else { cAux = hex } let xAux = hexToRgb(cAux) if (xAux) { setRed(xAux.r.toString()) setGreen(xAux.g.toString()) setBlue(xAux.b.toString()) } else { setRed('0') setGreen('0') setBlue('0') } setDisplay('RGB') } /* Hooks */ useEffect(() => { setHex(exceptThis(color, '#')) setCol(color) }, []) return (<> {title} {'Cor escolhida'} { (display === 'RGB') ? (<> { setRed(event) setCol(rgbToHex(parseInt(event), parseInt(green), parseInt(blue))) }} style={styles.colorInput} value={red} /> { setGreen(event) setCol(rgbToHex(parseInt(red), parseInt(event), parseInt(blue))) }} style={styles.colorInput} value={green} /> { setBlue(event) setCol(rgbToHex(parseInt(red), parseInt(green), parseInt(event))) }} style={styles.colorInput} value={blue} /> ) : (<> { setHex(event) return (event.length === 3 || event.length === 6) ? setCol(`#${event}`) : null }} style={{ height: 50, width: 260, marginRight: 10 }} value={hex} /> )} (display === 'RGB') ? handleRgbToHex() : handleHexToRgb()} /> ) } Color.displayName = 'Edit.Color' export default Color