@zohodesk/hooks
Version:
Unified Component Library - Hooks
76 lines (69 loc) • 2.35 kB
JavaScript
import { useEffect, useRef } from 'react';
import useEvent from "../utils/useEvent";
function useElementResize() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
minWidth = 0,
maxWidth = Infinity,
minHeight = 0,
maxHeight = Infinity,
resizeType = 'width',
// 'both', 'height', 'width'
handleResizeCallback,
needContainerSizeChange = true
} = props;
const containerRef = useRef();
const barRef = useRef();
const containerRect = useRef({
width: 0,
height: 0
});
const mousePos = useRef({
x: 0,
y: 0
});
const initializeResize = useEvent(e => {
mousePos.current.x = e.pageX;
mousePos.current.y = e.pageY;
containerRect.current.width = containerRef.current.clientWidth;
containerRect.current.height = containerRef.current.clientHeight;
window.addEventListener('mousemove', handleResize);
window.addEventListener('mouseup', handleResizeStop);
});
const handleResize = useEvent(e => {
let width = containerRect.current.width + (e.pageX - mousePos.current.x);
let height = containerRect.current.height + (e.pageY - mousePos.current.y);
width = Math.min(Math.max(width, minWidth), maxWidth);
height = Math.min(Math.max(height, minHeight), maxHeight);
let newRect = {};
if (resizeType === 'height') {
needContainerSizeChange ? containerRef.current.style.height = `${height}px` : null;
newRect.height = height;
} else if (resizeType === 'width') {
needContainerSizeChange ? containerRef.current.style.width = `${width}px` : null;
newRect.width = width;
} else {
if (needContainerSizeChange) {
containerRef.current.style.height = `${height}px`;
containerRef.current.style.width = `${width}px`;
}
newRect.height = height;
newRect.width = width;
}
handleResizeCallback && handleResizeCallback(newRect);
});
function handleResizeStop() {
window.removeEventListener('mousemove', handleResize);
}
useEffect(() => {
barRef.current.addEventListener('mousedown', initializeResize);
return () => {
barRef.current.removeEventListener('mousedown', initializeResize);
};
}, []);
return {
setContainerRef: containerRef,
setBarRef: barRef
};
}
export default useElementResize;