Skip to content

Commit

Permalink
add useDragResize hook
Browse files Browse the repository at this point in the history
  • Loading branch information
UpperCod committed Aug 7, 2022
1 parent 3fd3a68 commit e5f81ad
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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/*"
Expand Down
50 changes: 50 additions & 0 deletions src/use-drag-resize/use-drag-resize.ts
Original file line number Diff line number Diff line change
@@ -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];
}

0 comments on commit e5f81ad

Please sign in to comment.