From fcb07257f0208612816c888b7b6f9b8ac4c4570e Mon Sep 17 00:00:00 2001 From: sanine Date: Sun, 5 Jun 2022 22:31:03 -0500 Subject: add draggable 'windows' --- src/Draggable/Draggable.js | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/Draggable/Draggable.js (limited to 'src/Draggable/Draggable.js') diff --git a/src/Draggable/Draggable.js b/src/Draggable/Draggable.js new file mode 100644 index 0000000..0b35a88 --- /dev/null +++ b/src/Draggable/Draggable.js @@ -0,0 +1,57 @@ +import h from '../Util/DomUtil.js'; +import { clamp } from '../Util/Util.js'; + +class DraggableWindow { + constructor(title) { + this.div = h('div', { 'class': 'draggable-window', 'style': 'position: absolute; z-index: 9' }); + this.header = h('div', title, { 'class': 'draggable-header', 'style': 'cursor: move; z-index: 10' }); + this.div.appendChild(this.header); + + this.lastPosition = { x: 0, y: 0 }; + this.position = { x: 0, y: 0 }; + + this.div.addEventListener('mousedown', e => { + if (e.button != 0) return; + e.preventDefault(); + this.position = { + x: this.div.offsetLeft, + y: this.div.offsetTop, + }; + this.lastPosition = { + x: e.clientX, + y: e.clientY, + }; + document.onmousemove = e => { + const dx = e.clientX - this.lastPosition.x; + const dy = e.clientY - this.lastPosition.y; + + this.position.x += dx; + this.position.y += dy; + + this.lastPosition = { + x: e.clientX, + y: e.clientY, + }; + + this.div.style.left = `${clamp(this.position.x, 0, window.innerWidth-20)}px`; + this.div.style.top = `${clamp(this.position.y, 0, window.innerHeight-20)}px`; + }; + document.onmouseup = () => { + document.onmousemove = null; + document.onmouseup = null; + }; + }); + + document.body.appendChild(this.div); + } + + appendChild(element) { + this.div.appendChild(element); + } + + setTitle(title) { + this.header.textContent = title; + } +} + +export default DraggableWindow; -- cgit v1.2.1