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

useResizeDrag.ts

141 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 /** Pointer widths are clamped to these before `resize` sees them. */
12 bounds: ResizeBounds;
13 resize: (width: number) => number;
14 finish: (width: number, moved: boolean) => void;
15 cleanup?: (committed: boolean) => void;
17​
18function clampToBounds(width: number, bounds: ResizeBounds): number {
19 return Math.max(bounds.min, Math.min(bounds.max, width));
21​
22interface ActiveDrag<T extends HTMLElement> {
23 session: ResizeSession;
24 target: T;
25 pointerId: number;
26 startX: number;
27 pendingX: number;
28 width: number;
29 moved: boolean;
30 frame: number | null;
31 onBlur: () => void;
33​
34function createResizeDrag<T extends HTMLElement>() {
35 let drag: ActiveDrag<T> | null = null;
36​
37 const flush = () => {
38 const active = drag;
39 if (!active) return;
40 const delta = (active.pendingX - active.startX) * (active.session.edge === "left" ? -1 : 1);
41 if (Math.abs(delta) > 2) active.moved = true;
42 active.width = active.session.resize(
43 clampToBounds(active.session.width + delta, active.session.bounds),
44 );
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(true);
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 // Leaving the window mid-drag commits where the pointer was.
95 const onBlur = () => finish(true);
96 window.addEventListener("blur", onBlur);
97 drag = {
98 session,
99 target: event.currentTarget,
100 pointerId: event.pointerId,
101 startX: event.clientX,
102 pendingX: event.clientX,
103 width: session.width,
104 moved: false,
105 frame: null,
106 onBlur,
107 };
108 document.body.style.cursor = "col-resize";
109 document.body.style.userSelect = "none";
110 },
111 onPointerMove(event: PointerEvent<T>) {
112 const active = drag;
113 if (!active || active.pointerId !== event.pointerId) return;
114 event.preventDefault();
115 active.pendingX = event.clientX;
116 if (Math.abs(event.clientX - active.startX) > 2) active.moved = true;
117 if (active.frame !== null) return;
118 active.frame = requestAnimationFrame(() => {
119 active.frame = null;
120 flush();
121 });
122 },
123 onPointerUp: (event: PointerEvent<T>) => end(event, true),
124 onPointerCancel: (event: PointerEvent<T>) => end(event, false),
125 onLostPointerCapture: (event: PointerEvent<T>) => end(event, false),
126 };
128​
129/**
130 * A pointer drag that resizes along one edge. The session `start` returns owns
131 * everything the drag needs, so options read at pointer-down hold for the whole
132 * drag. Attach `ref` to the handle so unmounting it abandons the drag.
133 */
134export function useResizeDrag<T extends HTMLElement>(
135 start: (event: PointerEvent<T>) => ResizeSession | null,
136) {
137 // Created once: `ref` must keep its identity, or a re-render mid-drag would run its cleanup.
138 const [drag] = useState(createResizeDrag<T>);
139 const { begin, ...rest } = drag;
140 return { ...rest, onPointerDown: (event: PointerEvent<T>) => begin(event, start) };