view src/alternatives/interactjs.html @ 4:0130ae25ef94

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

<!doctype html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<style>
			@import "/site.css";

			div[drag] {
				border: 1px solid;
				margin: 8px;
				padding: 8px;
				touch-action: none;
				background-color: LightGreen;
			}
		</style>
		<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.js"></script>
		<script>
			'use strict';

			let dxDrag, dyDrag;

			function dragStartListener(event) {
				dxDrag = 0;
				dyDrag = 0;
			}

			function dragMoveListener(event) {
				dxDrag += event.dx;
				dyDrag += event.dy;
				event.target.style.transform = `translate(${dxDrag}px, ${dyDrag}px)`;
			}

			function dragEndListener(event) {
				event.target.style.transform = null;
			}

			function indexOf(a,el) {
				for( let i=0; i<a.length; i++ ) {
					if( a[i] === el )
						return i;
				}
				return -1;
			}

			function dragEnterListener(event) {
				//return;
				console.log(event);
				let entered = event.target;
				let dragging = event.relatedTarget;
				if( entered === dragging )
					return;
				let divs = document.querySelectorAll('div[drag]');
				let iEntered = indexOf(divs,entered);
				let iDragging = indexOf(divs,dragging);
				console.log(iDragging+' '+iEntered);
				let parent = entered.parentNode;
				if( iDragging < iEntered ) {
					let next = divs[iEntered+1];
					if( next ) {
						parent.insertBefore( dragging, next );
					} else {
						parent.appendChild( dragging );
					}
				} else {
					parent.insertBefore( dragging, entered );
				}
			}

			function init() {
				let dad = interact('div[drag]');
				dad.draggable({
					autoScroll: true,
					listeners: {
						start: dragStartListener,
						move: dragMoveListener,
						end: dragEndListener,
					}
				});
				dad.dropzone({
					ondragenter: dragEnterListener,
				});
			}
		</script>
	</head>
	<body>
		<h1><a href="https://interactjs.io/">interact.js</a></h1>

		<p>This has a number of problems.  First, it is clearly too complicated.  And this means that it isn't on just one JavaScript file.  One has to use the modern horror of <b>npm</b> to get it (which I refuse to do).  The suggested way of handling dragging doesn't work when the DOM changes, as the example below shows.  There is probably some complicated way around this, but I can't be bothered given the other issues.</p>

		<div>
		<script>
			for( let i=1; i<=10; i++ ) {
				document.write(`
			<div drag id="${i}">${i} - drag me</div>
`				);
			}
		</script>
		</div>
	</body>
	<script> init(); </script>
</html>