"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useComputeControlledOrUncontrolledValue = useComputeControlledOrUncontrolledValue;
var _compose = require("@wordpress/compose");
var _element = require("@wordpress/element");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Used to determine, via an internal heuristics, whether an `undefined` value
 * received for the `value` prop should be interpreted as the component being
 * used in uncontrolled mode, or as an "empty" value for controlled mode.
 *
 * @param valueProp The received `value`
 */
function useComputeControlledOrUncontrolledValue(valueProp) {
  const isInitialRenderRef = (0, _element.useRef)(true);
  const prevValueProp = (0, _compose.usePrevious)(valueProp);
  const prevIsControlledRef = (0, _element.useRef)(false);
  (0, _element.useEffect)(() => {
    if (isInitialRenderRef.current) {
      isInitialRenderRef.current = false;
    }
  }, []);

  // Assume the component is being used in controlled mode on the first re-render
  // that has a different `valueProp` from the previous render.
  const isControlled = prevIsControlledRef.current || !isInitialRenderRef.current && prevValueProp !== valueProp;
  (0, _element.useEffect)(() => {
    prevIsControlledRef.current = isControlled;
  }, [isControlled]);
  if (isControlled) {
    // When in controlled mode, use `''` instead of `undefined`
    return {
      value: valueProp !== null && valueProp !== void 0 ? valueProp : '',
      defaultValue: undefined
    };
  }

  // When in uncontrolled mode, the `value` should be intended as the initial value
  return {
    value: undefined,
    defaultValue: valueProp
  };
}
//# sourceMappingURL=utils.js.map