-
Notifications
You must be signed in to change notification settings - Fork 4k
/
hex-input.tsx
55 lines (50 loc) · 1.17 KB
/
hex-input.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* External dependencies
*/
import { colord, Colord } from 'colord';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { Text } from '../text';
import { Spacer } from '../spacer';
import { space } from '../ui/utils/space';
import { ColorHexInputControl } from './styles';
import { COLORS } from '../utils/colors-values';
interface HexInputProps {
color: Colord;
onChange: ( nextColor: Colord ) => void;
enableAlpha: boolean;
}
export const HexInput = ( { color, onChange, enableAlpha }: HexInputProps ) => {
const handleValidate = ( value: string ) => {
if ( ! colord( '#' + value ).isValid() ) {
throw new Error( 'Invalid hex color input' );
}
};
return (
<ColorHexInputControl
prefix={
<Spacer
as={ Text }
marginLeft={ space( 3.5 ) }
color={ COLORS.ui.theme }
lineHeight={ 1 }
>
#
</Spacer>
}
value={ color.toHex().slice( 1 ).toUpperCase() }
onChange={ ( nextValue ) => {
onChange( colord( '#' + nextValue ) );
} }
onValidate={ handleValidate }
maxLength={ enableAlpha ? 8 : 6 }
label={ __( 'Hex color' ) }
hideLabelFromVision
/>
);
};