"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useOuterClick = useOuterClick;

var _react = require("react");

function useOuterClick(callback) {
  var callbackRef = (0, _react.useRef)(); // initialize mutable ref, which stores callback

  var innerRef = (0, _react.useRef)(); // returned to client, who marks "border" element
  // update cb on each render, so second useEffect has access to current value

  (0, _react.useEffect)(function () {
    callbackRef.current = callback;
  });
  (0, _react.useEffect)(function () {
    document.addEventListener("click", handleClick);
    return function () {
      return document.removeEventListener("click", handleClick);
    };

    function handleClick(e) {
      if (innerRef.current && callbackRef.current && !innerRef.current.contains(e.target)) callbackRef.current(e);
    }
  }, []); // no dependencies -> stable click listener

  return innerRef; // convenience for client (doesn't need to init ref himself)
}