|
| 1 | +import { Ref, useState, useHost, useEffect } from "atomico"; |
| 2 | +import { useListener } from "../use-listener/use-listener"; |
| 3 | +import { useDebounceState } from "../use-debounce-state/use-debounce-state"; |
| 4 | + |
| 5 | +export function useDragResize( |
| 6 | + ref: Ref, |
| 7 | + rootState: number[] = [1, 1] |
| 8 | +): [boolean, number, number] { |
| 9 | + const host = useHost(); |
| 10 | + const [active, setActive] = useState(false); |
| 11 | + const [[x, y], setValue] = useDebounceState(1, rootState, "fps"); |
| 12 | + |
| 13 | + useEffect(() => setValue(rootState), rootState); |
| 14 | + |
| 15 | + const start = () => setActive(true); |
| 16 | + const end = () => setActive(false); |
| 17 | + |
| 18 | + useListener(ref, "mousedown", start); |
| 19 | + |
| 20 | + useListener(host, "mouseup", end); |
| 21 | + |
| 22 | + useListener(host, "mouseleave", end); |
| 23 | + |
| 24 | + useListener(ref, "touchstart", start); |
| 25 | + |
| 26 | + useListener(host, "touchend", end); |
| 27 | + |
| 28 | + useListener(host, "touchmove", (event: TouchEvent) => { |
| 29 | + const { |
| 30 | + targetTouches: [touche], |
| 31 | + } = event; |
| 32 | + const rect = host.current.getBoundingClientRect(); |
| 33 | + const offsetX = touche.pageX - rect.x; |
| 34 | + const offsetY = touche.pageY - rect.y; |
| 35 | + const { current } = host; |
| 36 | + setValue([offsetX / current.clientWidth, offsetY / current.clientHeight]); |
| 37 | + }); |
| 38 | + |
| 39 | + useListener(host, "mousemove", (event: MouseEvent) => { |
| 40 | + if (active) { |
| 41 | + const { current } = host; |
| 42 | + setValue([ |
| 43 | + event.offsetX / current.clientWidth, |
| 44 | + event.offsetY / current.clientHeight, |
| 45 | + ]); |
| 46 | + } |
| 47 | + }); |
| 48 | + |
| 49 | + return [active, x, y]; |
| 50 | +} |
0 commit comments