Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useResizeDrag.ts

140 lines4.6 KB

1import { type PointerEvent, useState } from "react";
2​
3export interface ResizeBounds {
4 readonly min: number;
5 readonly max: number;
6}
7​
8interface ResizeSession {
9 width: number;
10 edge: "left" | "right";
11 /** The first `resize` argument is clamped; the second retains pointer intent. */
12 bounds: ResizeBounds;
13 resize: (width: number, rawWidth: number) => number;
14 cancelOnInterrupt?: boolean;
15 finish: (width: number, moved: boolean) => void;
16 cleanup?: (committed: boolean) => void;
18​
19function clampToBounds(width: number, bounds: ResizeBounds): number {
20 return Math.max(bounds.min, Math.min(bounds.max, width));
22​
23interface ActiveDrag<T extends HTMLElement> {
24 session: ResizeSession;
25 target: T;
26 pointerId: number;
27 startX: number;
28 pendingX: number;
29 width: number;
30 moved: boolean;
31 frame: number | null;
32 onBlur: () => void;
34​
35function createResizeDrag<T extends HTMLElement>() {
36 let drag: ActiveDrag<T> | null = null;
37​
38 const flush = () => {
39 const active = drag;
40 if (!active) return;
41 const delta = (active.pendingX - active.startX) * (active.session.edge === "left" ? -1 : 1);
42 if (Math.abs(delta) > 2) active.moved = true;
43 const rawWidth = active.session.width + delta;
44 active.width = active.session.resize(clampToBounds(rawWidth, active.session.bounds), rawWidth);
45 };
46​
47 const finish = (commit: boolean) => {
48 const active = drag;
49 if (!active) return;
50 if (active.frame !== null) cancelAnimationFrame(active.frame);
51 window.removeEventListener("blur", active.onBlur);
52 if (commit) flush();
53 // Release can synchronously dispatch lostpointercapture.
54 drag = null;
55 try {
56 if (active.target.hasPointerCapture(active.pointerId)) {
57 active.target.releasePointerCapture(active.pointerId);
58 }
59 } catch {}
60 document.body.style.removeProperty("cursor");
61 document.body.style.removeProperty("user-select");
62 active.session.cleanup?.(commit);
63 if (commit) active.session.finish(active.width, active.moved);
64 };
65​
66 const end = (event: PointerEvent<T>, usePosition: boolean) => {
67 const active = drag;
68 if (!active || active.pointerId !== event.pointerId) return;
69 event.preventDefault();
70 if (usePosition) active.pendingX = event.clientX;
71 finish(usePosition || !active.session.cancelOnInterrupt);
72 };
73​
74 return {
75 ref: (node: T | null) => (node === null ? undefined : () => finish(false)),
76 cancel: () => finish(false),
77 refresh(bounds?: ResizeBounds) {
78 if (!drag) return;
79 if (bounds) drag.session.bounds = bounds;
80 flush();
81 },
82 begin(event: PointerEvent<T>, start: (event: PointerEvent<T>) => ResizeSession | null) {
83 if (event.button !== 0 || drag) return;
84 const session = start(event);
85 if (!session) return;
86 try {
87 event.currentTarget.setPointerCapture(event.pointerId);
88 } catch {
89 session.cleanup?.(false);
90 return;
91 }
92 event.preventDefault();
93 event.stopPropagation();
94 const onBlur = () => finish(!session.cancelOnInterrupt);
95 window.addEventListener("blur", onBlur);
96 drag = {
97 session,
98 target: event.currentTarget,
99 pointerId: event.pointerId,
100 startX: event.clientX,
101 pendingX: event.clientX,
102 width: session.width,
103 moved: false,
104 frame: null,
105 onBlur,
106 };
107 document.body.style.cursor = "col-resize";
108 document.body.style.userSelect = "none";
109 },
110 onPointerMove(event: PointerEvent<T>) {
111 const active = drag;
112 if (!active || active.pointerId !== event.pointerId) return;
113 event.preventDefault();
114 active.pendingX = event.clientX;
115 if (Math.abs(event.clientX - active.startX) > 2) active.moved = true;
116 if (active.frame !== null) return;
117 active.frame = requestAnimationFrame(() => {
118 active.frame = null;
119 flush();
120 });
121 },
122 onPointerUp: (event: PointerEvent<T>) => end(event, true),
123 onPointerCancel: (event: PointerEvent<T>) => end(event, false),
124 onLostPointerCapture: (event: PointerEvent<T>) => end(event, false),
125 };
127​
128/**
129 * A pointer drag that resizes along one edge. The session `start` returns owns
130 * everything the drag needs, so options read at pointer-down hold for the whole
131 * drag. Attach `ref` to the handle so unmounting it abandons the drag.
132 */
133export function useResizeDrag<T extends HTMLElement>(
134 start: (event: PointerEvent<T>) => ResizeSession | null,
135) {
136 // Created once: `ref` must keep its identity, or a re-render mid-drag would run its cleanup.
137 const [drag] = useState(createResizeDrag<T>);
138 const { begin, ...rest } = drag;
139 return { ...rest, onPointerDown: (event: PointerEvent<T>) => begin(event, start) };