"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAnalyticsContent = useAnalyticsContent;
var _compat = require("preact/compat");
var _getAnalyticsContentFromRefs = _interopRequireDefault(require("./getAnalyticsContentFromRefs"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
 * Use this hook to retrieve rendered content for use in analytics events.
 * It accepts `onMount` and `onUnmount` event handlers, which will be called
 * with the rendered textContent of the desired element. It grabs text content
 * from the first element that has it, in order of the returned refs array.
 * In the example below, it will favor content from `headingRef` (first ref)
 * but will fall back to `bodyRef` (second ref) if no content is found:
 *
 * const [headingRef, bodyRef] = useAnalyticsContent({
 *   onMount: (content: string | undefined) => {
 *     if (!content) {
 *       console.error('No content found for [component-name] analytics event');
 *       return;
 *     }
 *     sendLinkEvent({
 *       event_name: 'alert_impression',
 *       heading: content,
 *       type: variation,
 *     });
 *   }
 * })
 *
 * return (
 *   <div>
 *     <h1 ref={headingRef}>Hello World</h1>
 *     <p ref={bodyRef}>
 *       I'm some body text
 *     </p>
 *   </div>
 * )
 */
function useAnalyticsContent(_ref) {
  let {
    onMount,
    onUnmount
  } = _ref;
  // Three refs should be enough to support fallback content. Add more in the future if needed
  const refs = [(0, _compat.useRef)(), (0, _compat.useRef)(), (0, _compat.useRef)()];

  // eslint-disable-next-line react-hooks/exhaustive-deps
  // According to this lint rule, we need to include all the dependencies of this function in the
  // dependency array. However, in order for this useEffect to only fire on first render, we would
  // need to memoize the two callback functions. This is an unnecessary burden on the implementing
  // class, and there isn't a good way to memoize the props we receive here because they *also*
  // have dependencies that should be listed but are unknown. This assumes that the onMount and
  // onUnmount do not have a reason to change between renders.
  (0, _compat.useEffect)(() => {
    const content = (0, _getAnalyticsContentFromRefs.default)(refs);
    onMount(content);
    return () => {
      if (onUnmount) onUnmount(content);
    };
  }, []);
  return refs;
}