'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');

var CLOSE_DOWN_RATIO = 0.25;
var isInteractive = function isInteractive(target) {
  return target instanceof Element && Boolean(target.closest('button, a, input, textarea, select, [role="button"]'));
};
var useBottomSheetDrag = function useBottomSheetDrag(args) {
  var panelRef = args.panelRef,
    handleRef = args.handleRef,
    enabled = args.enabled,
    onClose = args.onClose;
  React.useEffect(function () {
    var panel = panelRef.current;
    var handle = handleRef.current;
    if (!enabled || !panel || !handle) {
      return undefined;
    }
    var startY = 0;
    var currentY = 0;
    var startHeight = 0;
    var tracking = false;
    var onPointerMove = function onPointerMove(event) {
      if (!tracking) {
        return;
      }
      currentY = event.clientY;
      var deltaY = currentY - startY;
      if (deltaY > 0) {
        panel.style.transform = "translateY(".concat(deltaY, "px)");
      }
      if (event.cancelable) {
        event.preventDefault();
      }
    };
    var onPointerEnd = function onPointerEnd() {
      if (!tracking) {
        return;
      }
      tracking = false;
      window.removeEventListener('pointermove', onPointerMove);
      window.removeEventListener('pointerup', onPointerEnd);
      window.removeEventListener('pointercancel', onPointerEnd);
      var deltaY = currentY - startY;
      panel.style.transition = '';
      panel.style.transform = '';
      if (deltaY > startHeight * CLOSE_DOWN_RATIO) {
        onClose();
      }
    };
    var onPointerDown = function onPointerDown(event) {
      if (isInteractive(event.target)) {
        return;
      }
      tracking = true;
      startY = event.clientY;
      currentY = event.clientY;
      startHeight = panel.offsetHeight;
      panel.style.transition = 'none';
      window.addEventListener('pointermove', onPointerMove, {
        passive: false
      });
      window.addEventListener('pointerup', onPointerEnd);
      window.addEventListener('pointercancel', onPointerEnd);
      event.preventDefault();
    };
    handle.addEventListener('pointerdown', onPointerDown);
    return function () {
      handle.removeEventListener('pointerdown', onPointerDown);
      window.removeEventListener('pointermove', onPointerMove);
      window.removeEventListener('pointerup', onPointerEnd);
      window.removeEventListener('pointercancel', onPointerEnd);
    };
  }, [enabled, panelRef, handleRef, onClose]);
};

exports.useBottomSheetDrag = useBottomSheetDrag;
