UNPKG

@wordpress/components

Version:
279 lines (233 loc) 10.2 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.UnitControl = void 0; Object.defineProperty(exports, "parseQuantityAndUnitFromRawValue", { enumerable: true, get: function () { return _utils.parseQuantityAndUnitFromRawValue; } }); Object.defineProperty(exports, "useCustomUnits", { enumerable: true, get: function () { return _utils.useCustomUnits; } }); var _element = require("@wordpress/element"); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _classnames = _interopRequireDefault(require("classnames")); var _deprecated = _interopRequireDefault(require("@wordpress/deprecated")); var _i18n = require("@wordpress/i18n"); var inputControlActionTypes = _interopRequireWildcard(require("../input-control/reducer/actions")); var _unitControlStyles = require("./styles/unit-control-styles"); var _unitSelectControl = _interopRequireDefault(require("./unit-select-control")); var _utils = require("./utils"); var _hooks = require("../utils/hooks"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * External dependencies */ /** * WordPress dependencies */ 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 = _utils.CSS_UNITS, value: valueProp, onBlur: onBlurProp, onFocus: onFocusProp, ...props } = unitControlProps; if ('unit' in unitControlProps) { (0, _deprecated.default)('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 = (0, _element.useMemo)(() => (0, _utils.getUnitsWithCurrentUnit)(nonNullValueProp, unitProp, unitsProp), [nonNullValueProp, unitProp, unitsProp]); const [parsedQuantity, parsedUnit] = (0, _utils.getParsedQuantityAndUnit)(nonNullValueProp, unitProp, units); const [unit, setUnit] = (0, _hooks.useControlledState)(units.length === 1 ? units[0].value : unitProp, { initial: parsedUnit, fallback: '' }); (0, _element.useEffect)(() => { if (parsedUnit !== undefined) { setUnit(parsedUnit); } }, [parsedUnit, setUnit]); // Stores parsed value for hand-off in state reducer. const refParsedQuantity = (0, _element.useRef)(undefined); const classes = (0, _classnames.default)('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 = (0, _utils.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] = (0, _utils.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 ? (0, _element.createElement)(_unitSelectControl.default, { "aria-label": (0, _i18n.__)('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 (0, _element.createElement)(_unitControlStyles.ValueInput, (0, _extends2.default)({ 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 } />; * }; * ``` */ const UnitControl = (0, _element.forwardRef)(UnforwardedUnitControl); exports.UnitControl = UnitControl; var _default = UnitControl; exports.default = _default; //# sourceMappingURL=index.js.map