view src/dad.js @ 4:0130ae25ef94

add drop
author Franklin Schmidt <fschmidt@gmail.com>
date Sat, 22 Apr 2023 21:17:53 -0600
parents 6d5e4b38b4fb
children 1293cb0d30da
line wrap: on
line source

'use strict';

let dad = {};

{
	// override these if needed
	dad.whatToDrag = function(draggable) {
		return draggable;
	};
	dad.onDrop = function(event) {};
	dad.onDropped = function(event) {};


	let original = null;
	let dragging = null;
	let touchX, touchY;

	function onMouseMove(event) {
		//console.log(event);
		event.preventDefault();
		let rect = dragging.getBoundingClientRect();
		dragging.style.left = `${rect.x+event.movementX}px`;
		let y = rect.y + event.movementY;
		if( y < 0 ) {
			window.scrollBy( 0, y );
		} else if( y + rect.height > window.innerHeight ) {
			window.scrollBy( 0, y + rect.height - window.innerHeight );
		}
		dragging.style.top = `${y}px`;
	}

	function onTouchMove(event) {
		let touches = event.touches;
		if( touches.length !== 1 )
			return;
		let touch = touches[0];
		let x = touch.clientX;
		let y = touch.clientY;
		event.movementX = x - touchX;
		event.movementY = y - touchY;
		touchX = x;
		touchY = y;
		onMouseMove(event);
	}

	function onMouseUp(event) {
		//console.log(event);
		dad.onDrop({
			draggable: original,
			dragged: dragging,
			mouseEvent: event,
		});
		original.removeAttribute('dad-original');
		dragging.parentNode.removeChild(dragging);
		document.removeEventListener('mousemove',onMouseMove);
		document.removeEventListener('mouseup',onMouseUp);
		document.removeEventListener('mousemove',onMouseMove);
		document.removeEventListener('touchend',onMouseUp);
		original.scrollIntoViewIfNeeded(false);
		let droppedEvent = {
			draggable: original,
		};
		original = null;
		dragging = null;
		dad.onDropped(droppedEvent);
	}

	function start(event) {
		//console.log(event);
		original = dad.whatToDrag(event.target);
		dragging = original.cloneNode(true);
		original.setAttribute('dad-original','');
		dragging.setAttribute('dad-dragging','');
		let rect = original.getBoundingClientRect();
		dragging.style.left = `${rect.x}px`;
		dragging.style.top = `${rect.y}px`;
		original.parentNode.appendChild(dragging);
	}

	function onMouseDown(event) {
		start(event);
		document.addEventListener('mousemove',onMouseMove);
		document.addEventListener('mouseup',onMouseUp);
	}

	function onTouchStart(event) {
		start(event);
		let touches = event.touches;
		if( touches.length !== 1 )
			return;
		let touch = touches[0];
		touchX = touch.clientX;
		touchY = touch.clientY;
		document.addEventListener('touchmove',onTouchMove);
		document.addEventListener('touchend',onMouseUp);
	}

	dad.setDraggable = function(el) {
		el.setAttribute('dad-drag','');
		el.addEventListener('mousedown',onMouseDown);
		el.addEventListener('touchstart',onTouchStart);
	};
}