"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useNativeDialogAnalytics = useNativeDialogAnalytics;
var _react = require("react");
var _getAnalyticsContentFromRefs = _interopRequireDefault(require("../analytics/getAnalyticsContentFromRefs"));
var _usePrevious = _interopRequireDefault(require("../utilities/usePrevious"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
 * This hook is for any component based on `NativeDialog` that needs analytics that fire
 * upon opening and closing. You provide it the `isOpen` prop being passed to the
 * `NativeDialog` and handlers for `onOpen` and `onClose`, which will be called with the
 * rendered heading content based on where you apply the ref this hook returns. Example:
 *
 * const headingRef = useNativeDialogAnalytics({
 *   isOpen: props.isOpen,
 *   onOpen: (content) => {
 *     // Send an event
 *   },
 *  onClose: (content) => {
 *     // Send an event
 *   }
 * })
 *
 * return (
 *   <NativeDialog {...props}>
 *     <h1 ref={headingRef}>Hello World</h1>
 *   </NativeDialog>
 * )
 */
function useNativeDialogAnalytics(_ref) {
  let {
    isOpen,
    onOpen,
    onClose
  } = _ref;
  const headingRef = (0, _react.useRef)();
  const prevIsOpen = (0, _usePrevious.default)(isOpen);
  (0, _react.useEffect)(() => {
    const headingContent = (0, _getAnalyticsContentFromRefs.default)([headingRef]);
    // We want to call onOpen when it's open once and only once.
    // We want to call onClose only when it was open and then closed.
    if (isOpen && isOpen !== prevIsOpen) {
      // It either started open or was closed and now is open
      onOpen(headingContent);
    } else if (!isOpen && prevIsOpen === true) {
      // Only trigger if it was previously open
      onClose(headingContent);
    }
  }, [isOpen, prevIsOpen]);
  return headingRef;
}