index.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var vue = require('vue');
  4. require('../../utils/index.js');
  5. var style = require('../../utils/dom/style.js');
  6. const useDraggable = (targetRef, dragRef, draggable, overflow) => {
  7. let transform = {
  8. offsetX: 0,
  9. offsetY: 0
  10. };
  11. const onMousedown = (e) => {
  12. const downX = e.clientX;
  13. const downY = e.clientY;
  14. const { offsetX, offsetY } = transform;
  15. const targetRect = targetRef.value.getBoundingClientRect();
  16. const targetLeft = targetRect.left;
  17. const targetTop = targetRect.top;
  18. const targetWidth = targetRect.width;
  19. const targetHeight = targetRect.height;
  20. const clientWidth = document.documentElement.clientWidth;
  21. const clientHeight = document.documentElement.clientHeight;
  22. const minLeft = -targetLeft + offsetX;
  23. const minTop = -targetTop + offsetY;
  24. const maxLeft = clientWidth - targetLeft - targetWidth + offsetX;
  25. const maxTop = clientHeight - targetTop - targetHeight + offsetY;
  26. const onMousemove = (e2) => {
  27. let moveX = offsetX + e2.clientX - downX;
  28. let moveY = offsetY + e2.clientY - downY;
  29. if (!(overflow == null ? void 0 : overflow.value)) {
  30. moveX = Math.min(Math.max(moveX, minLeft), maxLeft);
  31. moveY = Math.min(Math.max(moveY, minTop), maxTop);
  32. }
  33. transform = {
  34. offsetX: moveX,
  35. offsetY: moveY
  36. };
  37. if (targetRef.value) {
  38. targetRef.value.style.transform = `translate(${style.addUnit(moveX)}, ${style.addUnit(moveY)})`;
  39. }
  40. };
  41. const onMouseup = () => {
  42. document.removeEventListener("mousemove", onMousemove);
  43. document.removeEventListener("mouseup", onMouseup);
  44. };
  45. document.addEventListener("mousemove", onMousemove);
  46. document.addEventListener("mouseup", onMouseup);
  47. };
  48. const onDraggable = () => {
  49. if (dragRef.value && targetRef.value) {
  50. dragRef.value.addEventListener("mousedown", onMousedown);
  51. }
  52. };
  53. const offDraggable = () => {
  54. if (dragRef.value && targetRef.value) {
  55. dragRef.value.removeEventListener("mousedown", onMousedown);
  56. }
  57. };
  58. const resetPostion = () => {
  59. transform = {
  60. offsetX: 0,
  61. offsetY: 0
  62. };
  63. if (targetRef.value) {
  64. targetRef.value.style.transform = "none";
  65. }
  66. };
  67. vue.onMounted(() => {
  68. vue.watchEffect(() => {
  69. if (draggable.value) {
  70. onDraggable();
  71. } else {
  72. offDraggable();
  73. }
  74. });
  75. });
  76. vue.onBeforeUnmount(() => {
  77. offDraggable();
  78. });
  79. return {
  80. resetPostion
  81. };
  82. };
  83. exports.useDraggable = useDraggable;
  84. //# sourceMappingURL=index.js.map