GoScrobble/web/node_modules/uncontrollable/lib/esm/hook.js

58 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2022-04-25 02:47:15 +00:00
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { useCallback, useRef, useState } from 'react';
import * as Utils from './utils';
function useUncontrolledProp(propValue, defaultValue, handler) {
var wasPropRef = useRef(propValue !== undefined);
var _useState = useState(defaultValue),
stateValue = _useState[0],
setState = _useState[1];
var isProp = propValue !== undefined;
var wasProp = wasPropRef.current;
wasPropRef.current = isProp;
/**
* If a prop switches from controlled to Uncontrolled
* reset its value to the defaultValue
*/
if (!isProp && wasProp && stateValue !== defaultValue) {
setState(defaultValue);
}
return [isProp ? propValue : stateValue, useCallback(function (value) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (handler) handler.apply(void 0, [value].concat(args));
setState(value);
}, [handler])];
}
export { useUncontrolledProp };
export default function useUncontrolled(props, config) {
return Object.keys(config).reduce(function (result, fieldName) {
var _extends2;
var _ref = result,
defaultValue = _ref[Utils.defaultKey(fieldName)],
propsValue = _ref[fieldName],
rest = _objectWithoutPropertiesLoose(_ref, [Utils.defaultKey(fieldName), fieldName].map(_toPropertyKey));
var handlerName = config[fieldName];
var _useUncontrolledProp = useUncontrolledProp(propsValue, defaultValue, props[handlerName]),
value = _useUncontrolledProp[0],
handler = _useUncontrolledProp[1];
return _extends({}, rest, (_extends2 = {}, _extends2[fieldName] = value, _extends2[handlerName] = handler, _extends2));
}, props);
}