48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import { useState, useCallback, useRef } from 'react';
|
|
|
|
interface PaneResizeHandlers {
|
|
onPointerDown: (e: React.PointerEvent) => void;
|
|
onPointerMove: (e: React.PointerEvent) => void;
|
|
onPointerUp: () => void;
|
|
}
|
|
|
|
export function usePaneResize(
|
|
initialWidth: number,
|
|
minWidth: number,
|
|
maxWidth: number,
|
|
side: 'left' | 'right'
|
|
): [number, PaneResizeHandlers] {
|
|
const [width, setWidth] = useState(initialWidth);
|
|
const draggingRef = useRef(false);
|
|
|
|
const handlePointerDown = useCallback((e: React.PointerEvent) => {
|
|
e.preventDefault();
|
|
(e.target as HTMLElement).setPointerCapture(e.pointerId);
|
|
draggingRef.current = true;
|
|
}, []);
|
|
|
|
const handlePointerMove = useCallback(
|
|
(e: React.PointerEvent) => {
|
|
if (!draggingRef.current) return;
|
|
const newWidth =
|
|
side === 'left'
|
|
? Math.min(maxWidth, Math.max(minWidth, e.clientX))
|
|
: Math.min(maxWidth, Math.max(minWidth, window.innerWidth - e.clientX));
|
|
setWidth(newWidth);
|
|
},
|
|
[side, minWidth, maxWidth]
|
|
);
|
|
|
|
const handlePointerUp = useCallback(() => {
|
|
draggingRef.current = false;
|
|
}, []);
|
|
|
|
return [
|
|
width,
|
|
{
|
|
onPointerDown: handlePointerDown,
|
|
onPointerMove: handlePointerMove,
|
|
onPointerUp: handlePointerUp,
|
|
},
|
|
];
|
|
}
|