Files
aurora-admin/frameworks/ColorPicker.jsx
T

47 lines
1.9 KiB
React

import React, { useState } from 'react';
import './ColorPicker.css';
const DEFAULT_PRESETS = ['#2F54EB','#1D39C4','#10239E','#F5222D','#FA8C16','#52C41A','#13C2C2','#722ED1',
'#EB2F96','#FAAD14','#A0D911','#1890FF','#000000','#595959','#8C8C8C','#BFBFBF'];
export default function ColorPicker({ value = '#2F54EB', presets = DEFAULT_PRESETS, onChange }) {
const [hex, setHex] = useState(value);
const [alpha, setAlpha] = useState(1);
const n = parseInt(hex.slice(1), 16);
const preview = `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;
function emit(nextHex, nextAlpha) {
onChange && onChange({ hex: nextHex, alpha: nextAlpha });
}
function onHexInput(e) {
const v = e.target.value;
if (/^#[0-9a-fA-F]{6}$/.test(v)) { setHex(v); emit(v, alpha); }
}
return (
<div className="aa-colorpicker">
<div className="aa-colorpicker-presets">
{presets.map((c, i) => (
<div
key={i}
className={'aa-colorpicker-swatch' + (c.toLowerCase() === hex.toLowerCase() ? ' is-active' : '')}
style={{ background: c }}
onClick={() => { setHex(c); emit(c, alpha); }}
/>
))}
</div>
<div className="aa-colorpicker-row">
<div className="aa-colorpicker-preview" style={{ background: preview }} />
<input type="color" className="aa-colorpicker-native" value={hex} onChange={e => { setHex(e.target.value); emit(e.target.value, alpha); }} />
<input className="aa-colorpicker-hex" value={hex.toUpperCase()} maxLength={7} onChange={onHexInput} />
</div>
<div className="aa-colorpicker-alpha">
透明度
<input type="range" min="0" max="100" value={Math.round(alpha * 100)} onChange={e => { setAlpha(e.target.value / 100); emit(hex, e.target.value / 100); }} />
<span>{Math.round(alpha * 100)}%</span>
</div>
</div>
);
}