Skip to content

Commit e5f81ad

Browse files
committed
add useDragResize hook
1 parent 3fd3a68 commit e5f81ad

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@atomico/hooks",
33
"description": "Series of utilities in hooks format to extend the operation of Atomico",
4-
"version": "3.45.0",
4+
"version": "3.46.0",
55
"type": "module",
66
"workspaces": [
77
"src/*"
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)