"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.useUncontrolledProp = useUncontrolledProp; exports.default = useUncontrolled; var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _react = require("react"); var Utils = _interopRequireWildcard(require("./utils")); 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); } function useUncontrolledProp(propValue, defaultValue, handler) { var wasPropRef = (0, _react.useRef)(propValue !== undefined); var _useState = (0, _react.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, (0, _react.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])]; } 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 = (0, _objectWithoutPropertiesLoose2.default)(_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 (0, _extends3.default)({}, rest, (_extends2 = {}, _extends2[fieldName] = value, _extends2[handlerName] = handler, _extends2)); }, props); }