import classNames from "classnames"; import type { CSSProperties, MouseEvent as ReactMouseEvent } from "react"; import { useCallback, useEffect, useRef, useState } from "react"; import { createHandleDrag } from "./resizeDrag"; export interface ResizeHandleEvent { x: number; y: number; xStart: number; yStart: number; } interface Props { style?: CSSProperties; className?: string; onResizeStart?: () => void; onResizeEnd?: () => void; onResizeMove?: (e: ResizeHandleEvent) => void; onReset?: () => void; side: "left" | "right" | "top"; justify: "center" | "end" | "start"; /** Fills the space it is given, all of it taking the pointer, with its bar centred in it */ fill?: boolean; } export function ResizeHandle({ style, justify, className, onResizeStart, onResizeEnd, onResizeMove, onReset, side, fill = false, }: Props) { const vertical = side === "top"; const [isResizing, setIsResizing] = useState(false); const stopDrag = useRef<(() => void) | null>(null); // A handle that goes away mid-drag ends the drag, so its owner is not left resizing useEffect(() => () => stopDrag.current?.(), []); const handlePointerDown = useCallback( (e: ReactMouseEvent) => { stopDrag.current?.(); const drag = createHandleDrag({ vertical, xStart: e.clientX, yStart: e.clientY, onResizeStart: () => { onResizeStart?.(); setIsResizing(true); }, onResizeMove, onResizeEnd, }); function move(e: MouseEvent) { drag.move(e); } function removeListeners() { stopDrag.current = null; document.documentElement.removeEventListener("mousemove", move); document.documentElement.removeEventListener("mouseup", up); } function up() { removeListeners(); setIsResizing(false); drag.up(); } stopDrag.current = () => { removeListeners(); drag.abort(); }; document.documentElement.addEventListener("mousemove", move); document.documentElement.addEventListener("mouseup", up); }, [onResizeEnd, onResizeMove, onResizeStart, vertical], ); return (
{fill && (
)} {isResizing && (
)}
); }