import { Button, InputText } from 'exchange-elements/v2';
import { ChangeEvent, useMemo, useRef } from 'react';
import styles from './index.module.scss';
interface ColorFieldProps {
label: string;
value: string;
onValueChange: (value: string) => void;
}
function normalizeHex(value: string): string {
const next = value.trim();
if (!next) {
return '#000000';
}
const withHash = next.startsWith('#') ? next : `#${next}`;
if (/^#[0-9A-Fa-f]{6}$/.test(withHash)) {
return withHash;
}
return '#000000';
}
export const ColorField = ({ label, value, onValueChange }: ColorFieldProps) => {
const inputRef = useRef<HTMLInputElement | null>(null);
const normalizedValue = useMemo(() => normalizeHex(value), [value]);
return (
<div className={styles.field}>
<span className={styles.label}>{label}</span>
<div className={styles.colorFieldRow}>
<Button
className={styles.colorPreview}
style={{ backgroundColor: normalizedValue }}
onClick={() => inputRef.current?.click()}
children={}
/>
<input
ref={inputRef}
type="color"
className={styles.hiddenColorInput}
value={normalizedValue}
onChange={(event) => {
onValueChange(event.target.value);
}}
/>
<InputText
value={normalizedValue}
onChange={(event: ChangeEvent<HTMLInputElement>) => {
onValueChange(event.target.value);
}}
/>
</div>
</div>
);
};