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 / getTrackingClickHandler.js
Size: Mime:
import getTrackingAttributes from './getTrackingAttributes';

/**
 * Recursive helper function to retrieve the nearest tracking-enabled parent, if any
 *
 * We expect data attributes either on the clicked element or in its chain of parents as it's common to have
 * a <span> tag (often from a FormattedMessage) as child of the <a> or <button> carrying the tracking data attributes,
 * which is often the case when using @doodle/components' <Link> and <Button>
 *
 * @param {?HTMLElement} el An HTML element to inspect
 * @return {?HTMLElement} The element itself if it has tracking enabled otherwise null
 */
const getDataTrackingEl = el =>
  // eslint-disable-next-line no-nested-ternary
  el && el.dataset && el.dataset.tracking ? el : el.parentElement ? getDataTrackingEl(el.parentElement) : null;

/**
 * Helper function that returns a function that can be used as a click handler for all DOM elements
 * @param {Function} emit provided by redux-saga, used for emitting an event
 * @return {Function}
 */
const getTrackingClickHandler = emit => {
  const trackingClickHandler = event => {
    const { target } = event;
    const trackingEl = getDataTrackingEl(target);

    if (!trackingEl) {
      return;
    }

    const { href, valuesToTrack, isSameTabLink } = getTrackingAttributes(trackingEl);

    if (isSameTabLink) {
      event.preventDefault();
    }

    emit({ href, isSameTabLink, valuesToTrack });
  };
  return trackingClickHandler;
};

export default getTrackingClickHandler;
export { getDataTrackingEl };