"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = require("react");

/**
 * A hook for controlled value management.
 * In the case of passing the controlled value, the controlled value is returned, otherwise the value in state is returned.
 * Generally used for a component including controlled and uncontrolled modes.
 * @param controlledValue
 * @param defaultValue
 * @param formatValue
 */
function useControlled(controlledValue, defaultValue, formatValue) {
  var _useRef = (0, _react.useRef)(controlledValue !== undefined),
      isControlled = _useRef.current;

  var _useState = (0, _react.useState)(defaultValue),
      uncontrolledValue = _useState[0],
      setUncontrolledValue = _useState[1]; // If it is controlled, this directly returns the attribute value.


  var value = isControlled ? controlledValue : uncontrolledValue;
  value = formatValue ? formatValue(value) : value;
  var setValue = (0, _react.useCallback)(function (nextValue) {
    // Only update the value in state when it is not under control.
    if (!isControlled) {
      setUncontrolledValue(nextValue);
    }
  }, [isControlled]);
  return [value, setValue, isControlled];
}

var _default = useControlled;
exports.default = _default;