import { RGBA } from '@vev/utils'; import React, { useCallback, useEffect, useState } from 'react'; import { SilkeBox } from '../silke-box'; import tinycolor from 'tinycolor2'; import { SilkeSelectField } from '../silke-select-field'; import { SilkeTextField } from '../silke-text-field'; import { hexToRgb, isVariableV2 } from './color'; import { clamp, round } from 'lodash'; import { SilkeCssNumberField } from '../silke-css-number-field'; import { SilkeVariablesWrapper } from '../silke-variables-wrapper'; type ColorInfoProps = { rgba: RGBA; variableKey?: string; noTransparency?: boolean; onChange: (color: RGBA) => void; onVariableChange: (key: string) => void; }; const rgbLabels = ['r', 'g', 'b'] as (keyof RGBA)[]; export function ColorInfo({ rgba, variableKey, noTransparency, onChange, onVariableChange, }: ColorInfoProps) { const [format, setFormat] = useState('HEX'); const [tmpHex, setTmpHex] = useState(null); const [tmpRgb, setTmpRgb] = useState(rgba); const [hasFocus, setHasFocus] = useState(false); const [tmpA, setTempA] = useState( (rgba?.a === 0 ? rgba.a : rgba?.a ? Math.round(rgba.a * 100) : 100).toString(), ); const isVariable = !!variableKey; useEffect(() => { if (!hasFocus) { setTempA((rgba?.a === 0 ? rgba.a : rgba?.a ? Math.round(rgba.a * 100) : 100).toString()); setTmpRgb(rgba); } }, [rgba]); const handleOpacity = (opacity: string) => { const alpha = clamp(parseFloat(opacity), 0, 100); setTempA(opacity); onChange({ ...rgba, a: round(alpha / 100, 2) }); }; const handleRgb = (attr: string, value: number) => { const newRgba = { ...rgba, [attr]: value > 255 ? 255 : value }; setTmpRgb(newRgba); if (value) onChange(newRgba); }; const handleHex = useCallback( (hex: string) => { if (isVariableV2(hex)) { onVariableChange(hex); return; } setTmpHex(hex); onChange({ ...rgba, ...hexToRgb(hex.replace('#', '')) }); }, [rgba, onChange], ); return ( setFormat(change as string)} items={[ { value: 'HEX', label: 'HEX' }, { value: 'RGB', label: 'RGB' }, ]} disabled={isVariable} /> {format === 'HEX' ? ( setTmpHex(null)} /> ) : ( {rgbLabels.map((attr) => ( { handleRgb(attr, value as number); }} /> ))} )} setHasFocus(true)} onBlur={() => setHasFocus(false)} onChange={handleOpacity} disabled={noTransparency || isVariable} /> ); }