{"size": 996, "ext": "js", "max_stars_repo_path": "src/useDrag.js", "max_stars_repo_name": "jacekk/beautiful-react-hooks", "max_stars_repo_stars_event_min_datetime": "2020-08-14T15:05:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T14:33:41.000Z", "max_issues_repo_path": "src/useDrag.js", "max_issues_repo_name": "jacekk/beautiful-react-hooks", "max_issues_repo_issues_event_min_datetime": "2020-09-22T13:24:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T18:59:10.000Z", "max_forks_repo_path": "src/useDrag.js", "max_forks_repo_name": "jacekk/beautiful-react-hooks", "max_forks_repo_forks_event_min_datetime": "2021-05-27T08:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T08:03:58.000Z"}
{"max_stars_count": 2, "max_issues_count": 142, "max_forks_count": 1, "avg_line_length": 26.2105263158, "max_line_length": 106, "alphanum_fraction": 0.6696787149}
import { useState } from 'react';
import useDragEvents from './useDragEvents';

const defaultOptions = {
  dragImage: null,
  dragImageXOffset: 0,
  dragImageYOffset: 0,
  transfer: null,
  transferFormat: 'text',
};

const useDrag = (targetRef, options = defaultOptions) => {
  const { onDragStart, onDragEnd } = useDragEvents(targetRef, true);
  const [isDragging, setIsDragging] = useState(false);
  const opts = { ...defaultOptions, ...(options || {}) };

  onDragStart((event) => {
    setIsDragging(true);

    if (opts.dragImage) {
      const img = new Image();
      img.src = opts.dragImage;
      event.dataTransfer.setDragImage(img, opts.dragImageXOffset, opts.dragImageYOffset);
    }

    if (opts.transfer) {
      const data = typeof opts.transfer === 'object' ? JSON.stringify(opts.transfer) : `${opts.transfer}`;
      event.dataTransfer.setData(opts.transferFormat, data);
    }
  });

  onDragEnd(() => setIsDragging(false));

  return isDragging;
};

export default useDrag;
