From e5f81ad6c60c34d7f9ab0d91006667b9ce5cc8b3 Mon Sep 17 00:00:00 2001 From: UpperCod Date: Sun, 7 Aug 2022 12:46:34 -0400 Subject: [PATCH] add useDragResize hook --- package.json | 2 +- src/use-drag-resize/use-drag-resize.ts | 50 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/use-drag-resize/use-drag-resize.ts diff --git a/package.json b/package.json index 8fb632c..de27fe2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@atomico/hooks", "description": "Series of utilities in hooks format to extend the operation of Atomico", - "version": "3.45.0", + "version": "3.46.0", "type": "module", "workspaces": [ "src/*" diff --git a/src/use-drag-resize/use-drag-resize.ts b/src/use-drag-resize/use-drag-resize.ts new file mode 100644 index 0000000..eb3651c --- /dev/null +++ b/src/use-drag-resize/use-drag-resize.ts @@ -0,0 +1,50 @@ +import { Ref, useState, useHost, useEffect } from "atomico"; +import { useListener } from "../use-listener/use-listener"; +import { useDebounceState } from "../use-debounce-state/use-debounce-state"; + +export function useDragResize( + ref: Ref, + rootState: number[] = [1, 1] +): [boolean, number, number] { + const host = useHost(); + const [active, setActive] = useState(false); + const [[x, y], setValue] = useDebounceState(1, rootState, "fps"); + + useEffect(() => setValue(rootState), rootState); + + const start = () => setActive(true); + const end = () => setActive(false); + + useListener(ref, "mousedown", start); + + useListener(host, "mouseup", end); + + useListener(host, "mouseleave", end); + + useListener(ref, "touchstart", start); + + useListener(host, "touchend", end); + + useListener(host, "touchmove", (event: TouchEvent) => { + const { + targetTouches: [touche], + } = event; + const rect = host.current.getBoundingClientRect(); + const offsetX = touche.pageX - rect.x; + const offsetY = touche.pageY - rect.y; + const { current } = host; + setValue([offsetX / current.clientWidth, offsetY / current.clientHeight]); + }); + + useListener(host, "mousemove", (event: MouseEvent) => { + if (active) { + const { current } = host; + setValue([ + event.offsetX / current.clientWidth, + event.offsetY / current.clientHeight, + ]); + } + }); + + return [active, x, y]; +}