-
Notifications
You must be signed in to change notification settings - Fork 156
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
67 additions
and
49 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import { useState, useEffect, useCallback, RefObject } from "react"; | ||
|
||
interface IProps { | ||
containerRef: RefObject<HTMLDivElement | null>; | ||
dividerRef: RefObject<HTMLDivElement | null>; | ||
dividerWidth: number; | ||
} | ||
|
||
function useDrag({ containerRef, dividerRef, dividerWidth }: IProps) { | ||
const [width, setWidth] = useState(0); | ||
const [containerRect, setContainerRect] = useState<DOMRect | null>(null); | ||
|
||
useEffect(() => { | ||
const containerEl = containerRef.current; | ||
if (containerEl) { | ||
const fullWidth = containerEl.clientWidth; | ||
const containerRect = containerEl.getBoundingClientRect(); | ||
setContainerRect(containerRect); | ||
setWidth(fullWidth / 2); | ||
} | ||
}, []); | ||
const keepDragging = useCallback( | ||
(event: MouseEvent) => { | ||
const { clientX } = event; | ||
if (containerRect) { | ||
setWidth(clientX - containerRect.left); | ||
} | ||
}, | ||
[containerRect] | ||
); | ||
const stopDrag = useCallback(() => { | ||
document.removeEventListener("mousemove", keepDragging); | ||
document.removeEventListener("mouseup", stopDrag); | ||
}, [keepDragging]); | ||
const startDrag = useCallback(() => { | ||
document.addEventListener("mousemove", keepDragging); | ||
document.addEventListener("mouseup", stopDrag); | ||
}, [keepDragging, stopDrag]); | ||
useEffect(() => { | ||
const dividerEl = dividerRef.current; | ||
if (dividerEl) { | ||
dividerEl.addEventListener("mousedown", startDrag); | ||
} | ||
return () => { | ||
if (dividerEl) { | ||
dividerEl.removeEventListener("mousedown", startDrag); | ||
} | ||
}; | ||
}, [startDrag]); | ||
|
||
return { | ||
leftWidth: width, | ||
rightWidth: containerRect ? containerRect.width - width : 0, | ||
}; | ||
} | ||
|
||
export default useDrag; |