-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.tsx
307 lines (273 loc) · 7.92 KB
/
index.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/**
* External dependencies
*/
import type {
FocusEventHandler,
KeyboardEvent,
ForwardedRef,
SyntheticEvent,
ChangeEvent,
PointerEvent,
} from 'react';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import deprecated from '@wordpress/deprecated';
import { forwardRef, useMemo, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import type { WordPressComponentProps } from '../ui/context';
import * as inputControlActionTypes from '../input-control/reducer/actions';
import { ValueInput } from './styles/unit-control-styles';
import UnitSelectControl from './unit-select-control';
import {
CSS_UNITS,
getParsedQuantityAndUnit,
getUnitsWithCurrentUnit,
getValidParsedQuantityAndUnit,
} from './utils';
import { useControlledState } from '../utils/hooks';
import type { UnitControlProps, UnitControlOnChangeCallback } from './types';
import type { StateReducer } from '../input-control/reducer/state';
function UnforwardedUnitControl(
unitControlProps: WordPressComponentProps<
UnitControlProps,
'input',
false
>,
forwardedRef: ForwardedRef< any >
) {
const {
__unstableStateReducer: stateReducerProp,
autoComplete = 'off',
// @ts-expect-error Ensure that children is omitted from restProps
children,
className,
disabled = false,
disableUnits = false,
isPressEnterToChange = false,
isResetValueOnUnitChange = false,
isUnitSelectTabbable = true,
label,
onChange: onChangeProp,
onUnitChange,
size = 'default',
unit: unitProp,
units: unitsProp = CSS_UNITS,
value: valueProp,
onBlur: onBlurProp,
...props
} = unitControlProps;
if ( 'unit' in unitControlProps ) {
deprecated( 'UnitControl unit prop', {
since: '5.6',
hint: 'The unit should be provided within the `value` prop.',
version: '6.2',
} );
}
// The `value` prop, in theory, should not be `null`, but the following line
// ensures it fallback to `undefined` in case a consumer of `UnitControl`
// still passes `null` as a `value`.
const nonNullValueProp = valueProp ?? undefined;
const units = useMemo(
() => getUnitsWithCurrentUnit( nonNullValueProp, unitProp, unitsProp ),
[ nonNullValueProp, unitProp, unitsProp ]
);
const [ parsedQuantity, parsedUnit ] = getParsedQuantityAndUnit(
nonNullValueProp,
unitProp,
units
);
const [ unit, setUnit ] = useControlledState< string | undefined >(
units.length === 1 ? units[ 0 ].value : unitProp,
{
initial: parsedUnit,
fallback: '',
}
);
useEffect( () => {
if ( parsedUnit !== undefined ) {
setUnit( parsedUnit );
}
}, [ parsedUnit, setUnit ] );
// Stores parsed value for hand-off in state reducer.
const refParsedQuantity = useRef< number | undefined >( undefined );
const classes = classnames(
'components-unit-control',
// This class is added for legacy purposes to maintain it on the outer
// wrapper. See: https://github.com/WordPress/gutenberg/pull/45139
'components-unit-control-wrapper',
className
);
const handleOnQuantityChange = (
nextQuantityValue: number | string | undefined,
changeProps: {
event:
| ChangeEvent< HTMLInputElement >
| PointerEvent< HTMLInputElement >;
}
) => {
if (
nextQuantityValue === '' ||
typeof nextQuantityValue === 'undefined' ||
nextQuantityValue === null
) {
onChangeProp?.( '', changeProps );
return;
}
/*
* Customizing the onChange callback.
* This allows as to broadcast a combined value+unit to onChange.
*/
const onChangeValue = getValidParsedQuantityAndUnit(
nextQuantityValue,
units,
parsedQuantity,
unit
).join( '' );
onChangeProp?.( onChangeValue, changeProps );
};
const handleOnUnitChange: UnitControlOnChangeCallback = (
nextUnitValue,
changeProps
) => {
const { data } = changeProps;
let nextValue = `${ parsedQuantity ?? '' }${ nextUnitValue }`;
if ( isResetValueOnUnitChange && data?.default !== undefined ) {
nextValue = `${ data.default }${ nextUnitValue }`;
}
onChangeProp?.( nextValue, changeProps );
onUnitChange?.( nextUnitValue, changeProps );
setUnit( nextUnitValue );
};
const mayUpdateUnit = ( event: SyntheticEvent< HTMLInputElement > ) => {
if ( ! isNaN( Number( event.currentTarget.value ) ) ) {
refParsedQuantity.current = undefined;
return;
}
const [ validParsedQuantity, validParsedUnit ] =
getValidParsedQuantityAndUnit(
event.currentTarget.value,
units,
parsedQuantity,
unit
);
refParsedQuantity.current = validParsedQuantity;
if ( isPressEnterToChange && validParsedUnit !== unit ) {
const data = Array.isArray( units )
? units.find( ( option ) => option.value === validParsedUnit )
: undefined;
const changeProps = { event, data };
// The `onChange` callback already gets called, no need to call it explicitly.
onUnitChange?.( validParsedUnit, changeProps );
setUnit( validParsedUnit );
}
};
const handleOnBlur: FocusEventHandler< HTMLInputElement > = ( event ) => {
mayUpdateUnit( event );
onBlurProp?.( event );
};
const handleOnKeyDown = ( event: KeyboardEvent< HTMLInputElement > ) => {
const { key } = event;
if ( key === 'Enter' ) {
mayUpdateUnit( event );
}
};
/**
* "Middleware" function that intercepts updates from InputControl.
* This allows us to tap into actions to transform the (next) state for
* InputControl.
*
* @param state State from InputControl
* @param action Action triggering state change
* @return The updated state to apply to InputControl
*/
const unitControlStateReducer: StateReducer = ( state, action ) => {
const nextState = { ...state };
/*
* On commits (when pressing ENTER and on blur if
* isPressEnterToChange is true), if a parse has been performed
* then use that result to update the state.
*/
if ( action.type === inputControlActionTypes.COMMIT ) {
if ( refParsedQuantity.current !== undefined ) {
nextState.value = (
refParsedQuantity.current ?? ''
).toString();
refParsedQuantity.current = undefined;
}
}
return nextState;
};
let stateReducer: StateReducer = unitControlStateReducer;
if ( stateReducerProp ) {
stateReducer = ( state, action ) => {
const baseState = unitControlStateReducer( state, action );
return stateReducerProp( baseState, action );
};
}
const inputSuffix = ! disableUnits ? (
<UnitSelectControl
aria-label={ __( 'Select unit' ) }
disabled={ disabled }
isUnitSelectTabbable={ isUnitSelectTabbable }
onChange={ handleOnUnitChange }
size={ size }
unit={ unit }
units={ units }
onBlur={ onBlurProp }
/>
) : null;
let step = props.step;
/*
* If no step prop has been passed, lookup the active unit and
* try to get step from `units`, or default to a value of `1`
*/
if ( ! step && units ) {
const activeUnit = units.find( ( option ) => option.value === unit );
step = activeUnit?.step ?? 1;
}
return (
<ValueInput
type={ isPressEnterToChange ? 'text' : 'number' }
{ ...props }
autoComplete={ autoComplete }
className={ classes }
disabled={ disabled }
hideHTMLArrows
isPressEnterToChange={ isPressEnterToChange }
label={ label }
onBlur={ handleOnBlur }
onKeyDown={ handleOnKeyDown }
onChange={ handleOnQuantityChange }
ref={ forwardedRef }
size={ size }
suffix={ inputSuffix }
value={ parsedQuantity ?? '' }
step={ step }
__unstableStateReducer={ stateReducer }
/>
);
}
/**
* `UnitControl` allows the user to set a numeric quantity as well as a unit (e.g. `px`).
*
*
* @example
* ```jsx
* import { __experimentalUnitControl as UnitControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ value, setValue ] = useState( '10px' );
*
* return <UnitControl onChange={ setValue } value={ value } />;
* };
* ```
*/
export const UnitControl = forwardRef( UnforwardedUnitControl );
export { parseQuantityAndUnitFromRawValue, useCustomUnits } from './utils';
export default UnitControl;