@carbon/utilities
Version:
Utilities and helpers to drive consistency across software products using the Carbon Design System
2 lines (1 loc) • 1.44 kB
JavaScript
const b=({el:e,dragHandle:n,focusableDragHandle:i,dragStep:l,shiftDragStep:p})=>{n?(n.style.cursor="move",e.style.cursor="default"):e.style.cursor="move";let s=!1,f=0,c=0;const r=(t,o)=>{const d={detail:o,bubbles:!0};e.dispatchEvent(new CustomEvent(t,d))},m=t=>{if(t.key==="Enter"&&(s=!s),s?r("dragstart",{keyboard:!0}):r("dragend",{keyboard:!0}),!s)return;const o=t.shiftKey?p??32:l??8;switch(t.key){case"Enter":case" ":t.preventDefault();break;case"ArrowLeft":e.style.left=`${e.offsetLeft-o}px`;break;case"ArrowRight":e.style.left=`${e.offsetLeft+o}px`;break;case"ArrowUp":e.style.top=`${e.offsetTop-o}px`;break;case"ArrowDown":e.style.top=`${e.offsetTop+o}px`;break}},a=t=>{const o=t.target;!(o instanceof Node)||!(n?n.contains(o):e.contains(o))||(f=t.clientX-e.offsetLeft,c=t.clientY-e.offsetTop,s=!0,r("dragstart",{mouse:!0}),document.addEventListener("mousemove",u),document.addEventListener("mouseup",v,{once:!0}))},u=t=>{s&&(e.style.left=`${t.clientX-f}px`,e.style.top=`${t.clientY-c}px`)},v=()=>{s&&(s=!1,r("dragend",{mouse:!0}),document.removeEventListener("mousemove",u))};return n?n.addEventListener("mousedown",a):e.addEventListener("mousedown",a),i?.addEventListener("keydown",m),{cleanup:()=>{n?n.removeEventListener("mousedown",a):e.removeEventListener("mousedown",a),i?.removeEventListener("keydown",m),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",v)}}};export{b as makeDraggable};