@wordpress/components
Version:
UI components for WordPress.
250 lines (216 loc) • 8.44 kB
JavaScript
import _extends from "@babel/runtime/helpers/esm/extends";
import { createElement } from "@wordpress/element";
/**
* External dependencies
*/
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 * 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';
function UnforwardedUnitControl(unitControlProps, forwardedRef) {
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,
onFocus: onFocusProp,
...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 !== null && valueProp !== void 0 ? valueProp : undefined;
const units = useMemo(() => getUnitsWithCurrentUnit(nonNullValueProp, unitProp, unitsProp), [nonNullValueProp, unitProp, unitsProp]);
const [parsedQuantity, parsedUnit] = getParsedQuantityAndUnit(nonNullValueProp, unitProp, units);
const [unit, setUnit] = useControlledState(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(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, changeProps) => {
if (nextQuantityValue === '' || typeof nextQuantityValue === 'undefined' || nextQuantityValue === null) {
onChangeProp === null || onChangeProp === void 0 ? void 0 : 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 === null || onChangeProp === void 0 ? void 0 : onChangeProp(onChangeValue, changeProps);
};
const handleOnUnitChange = (nextUnitValue, changeProps) => {
const {
data
} = changeProps;
let nextValue = `${parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : ''}${nextUnitValue}`;
if (isResetValueOnUnitChange && (data === null || data === void 0 ? void 0 : data.default) !== undefined) {
nextValue = `${data.default}${nextUnitValue}`;
}
onChangeProp === null || onChangeProp === void 0 ? void 0 : onChangeProp(nextValue, changeProps);
onUnitChange === null || onUnitChange === void 0 ? void 0 : onUnitChange(nextUnitValue, changeProps);
setUnit(nextUnitValue);
};
const mayUpdateUnit = event => {
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 === null || onUnitChange === void 0 ? void 0 : onUnitChange(validParsedUnit, changeProps);
setUnit(validParsedUnit);
}
};
const handleOnBlur = event => {
mayUpdateUnit(event);
onBlurProp === null || onBlurProp === void 0 ? void 0 : onBlurProp(event);
};
const handleOnKeyDown = event => {
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 = (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) {
var _refParsedQuantity$cu;
nextState.value = ((_refParsedQuantity$cu = refParsedQuantity.current) !== null && _refParsedQuantity$cu !== void 0 ? _refParsedQuantity$cu : '').toString();
refParsedQuantity.current = undefined;
}
}
return nextState;
};
let stateReducer = unitControlStateReducer;
if (stateReducerProp) {
stateReducer = (state, action) => {
const baseState = unitControlStateReducer(state, action);
return stateReducerProp(baseState, action);
};
}
const inputSuffix = !disableUnits ? createElement(UnitSelectControl, {
"aria-label": __('Select unit'),
disabled: disabled,
isUnitSelectTabbable: isUnitSelectTabbable,
onChange: handleOnUnitChange,
size: size,
unit: unit,
units: units,
onBlur: onBlurProp,
onFocus: onFocusProp
}) : 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) {
var _activeUnit$step;
const activeUnit = units.find(option => option.value === unit);
step = (_activeUnit$step = activeUnit === null || activeUnit === void 0 ? void 0 : activeUnit.step) !== null && _activeUnit$step !== void 0 ? _activeUnit$step : 1;
}
return createElement(ValueInput, _extends({
type: isPressEnterToChange ? 'text' : 'number'
}, props, {
autoComplete: autoComplete,
className: classes,
disabled: disabled,
spinControls: "none",
isPressEnterToChange: isPressEnterToChange,
label: label,
onBlur: handleOnBlur,
onKeyDown: handleOnKeyDown,
onChange: handleOnQuantityChange,
ref: forwardedRef,
size: size,
suffix: inputSuffix,
value: parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : '',
step: step,
__unstableStateReducer: stateReducer,
onFocus: onFocusProp
}));
}
/**
* `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;
//# sourceMappingURL=index.js.map