Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/tracking / src / helpers / trackingClickHandler.js
Size: Mime:
import { getTrackingDataObject } from './getTrackingDataObject';
import { dispatchTrack } from './dispatchTrack';

/**
 * Recursive helper function to retrieve the nearest tracking enabled parent, if any
 *
 * @param {HTMLElement} el An HTML element to inspect
 * @return {?HTMLElement} The element itself if it has tracking enabled otherwise null
 */
// eslint-disable-next-line no-nested-ternary
const getTrackingEl = el => (el && el.dataset.track ? el : el.parentElement ? getTrackingEl(el.parentElement) : null);

/**
 * Helper function that returns a function that can be used as a click handler for all DOM elements
 *
 * We expect data attributes either on the clicked element or in its immediate parent because it's common that we have
 * a <span> tag as child of the <a> carrying tracking data. That's the case of @doodle/components <Link> and <Button>
 * In WEB-5188 we may want to recursively check for others parents
 * @param {MouseEvent} event
 * @return {undefined}
 */
const trackingClickHandler = async event => {
  const { target } = event;
  const trackingEl = getTrackingEl(target);

  if (!trackingEl) {
    return;
  }

  const trackingDataObject = getTrackingDataObject(trackingEl);
  const { href, isSameTabLink } = trackingDataObject;

  if (isSameTabLink) {
    event.preventDefault();
    try {
      await dispatchTrack(trackingDataObject);
    } catch (e) {
      console.warn('Error on click');
      console.error(e);
    }
    // TODO: WEB-5197 allow consumers to inject their router navigator function
    // otherwise we break their SPA behavior forcing full page reloads for tracked links
    window.location = href;
  } else {
    // If the link opens in a new tab, we don't need to await the promise resolution
    dispatchTrack(trackingDataObject);
  }
};

export { trackingClickHandler };