-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
117 lines (111 loc) · 2.57 KB
/
index.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* External dependencies
*/
import { isFinite } from 'lodash';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { compose, withInstanceId, withState } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { BaseControl, Button, Dashicon } from '../';
function RangeControl( {
className,
currentInput,
label,
value,
instanceId,
onChange,
beforeIcon,
afterIcon,
help,
allowReset,
initialPosition,
min,
max,
setState,
...props
} ) {
const id = `inspector-range-control-${ instanceId }`;
const currentInputValue = currentInput === null ? value : currentInput;
const resetValue = () => {
resetCurrentInput();
onChange();
};
const resetCurrentInput = () => {
if ( currentInput !== null ) {
setState( {
currentInput: null,
} );
}
};
const onChangeValue = ( event ) => {
const newValue = event.target.value;
const newNumericValue = parseInt( newValue, 10 );
// If the input value is invalid temporarily save it to the state,
// without calling on change.
if (
isNaN( newNumericValue ) ||
( min !== undefined && newNumericValue < min ) ||
( max !== undefined && newNumericValue > max )
) {
setState( {
currentInput: newValue,
} );
return;
}
// The input is valid, reset the local state property used to temporaly save the value,
// and call onChange with the new value as a number.
resetCurrentInput();
onChange( newNumericValue );
};
const initialSliderValue = isFinite( value ) ?
currentInputValue :
initialPosition || '';
return (
<BaseControl
label={ label }
id={ id }
help={ help }
className={ classnames( 'components-range-control', className ) }
>
{ beforeIcon && <Dashicon icon={ beforeIcon } /> }
<input
className="components-range-control__slider"
id={ id }
type="range"
value={ initialSliderValue }
onChange={ onChangeValue }
aria-describedby={ !! help ? id + '__help' : undefined }
min={ min }
max={ max }
{ ...props } />
{ afterIcon && <Dashicon icon={ afterIcon } /> }
<input
className="components-range-control__number"
type="number"
onChange={ onChangeValue }
aria-label={ label }
value={ currentInputValue }
min={ min }
max={ max }
onBlur={ resetCurrentInput }
{ ...props }
/>
{ allowReset &&
<Button onClick={ resetValue } disabled={ value === undefined }>
{ __( 'Reset' ) }
</Button>
}
</BaseControl>
);
}
export default compose( [
withInstanceId,
withState( {
currentInput: null,
} ),
] )( RangeControl );