Open History to see the last commit
1import * as Schema from "effect/Schema";
2import {
3 type PointerEvent as ReactPointerEvent,
4 useCallback,
5 useEffect,
6 useRef,
7 useState,
8} from "react";
9
10import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
11
12const WidthSchema = Schema.Finite;
13
14export interface UseResizableWidthOptions {
15 /** localStorage key the persisted width is stored under. */
16 readonly storageKey: string;
17 readonly defaultWidth: number;
18 readonly minWidth: number;
19 readonly maxWidth: number;
20 /**
21 * Which edge of the host element carries the drag handle:
22 * - "left" → panel grows leftward (right-anchored panels)
23 * - "right" → panel grows rightward (left-anchored panels)
24 */
25 readonly edge: "left" | "right";
26}
27
28export interface ResizableWidthHandlers {
29 readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
30 readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
31 readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
32 readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
33 readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
34}
35
36/**
37 * Width state for a side-anchored panel resized via a drag handle on the
38 * specified edge. Width is read from localStorage on mount and persisted on
39 * drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
40 *
41 * The hook updates an internal `width` state during drag (so the panel
42 * follows the cursor live) and only commits to localStorage when the user
43 * lifts the pointer.
44 */
45export function useResizableWidth(options: UseResizableWidthOptions): {
46 readonly width: number;
47 readonly handlers: ResizableWidthHandlers;
48} {
49 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
50
51 const clamp = useCallback(
52 (value: number): number => {
53 if (!Number.isFinite(value)) return defaultWidth;
54 return Math.max(minWidth, Math.min(maxWidth, value));
55 },
56 [defaultWidth, maxWidth, minWidth],
57 );
58
59 // No cross-tab subscription: panel width is per-window state.
60 const [width, setWidth] = useState<number>(() => {
61 if (typeof window === "undefined") return defaultWidth;
62 try {
63 const stored = getLocalStorageItem(storageKey, WidthSchema);
64 return clamp(stored ?? defaultWidth);
65 } catch (error) {
66 console.error("Could not read persisted panel width.", error);
67 return defaultWidth;
68 }
69 });
70
71 const clampedWidth = clamp(width);
72
73 const dragStateRef = useRef<{
74 pointerId: number;
75 startX: number;
76 startWidth: number;
77 pending: number;
78 rafId: number | null;
79 target: HTMLElement;
80 } | null>(null);
81
82 const releasePointer = useCallback((pointerId: number) => {
83 const state = dragStateRef.current;
84 if (!state) return;
85 // Clear first because releasing capture can trigger another cleanup.
86 dragStateRef.current = null;
87 if (state.rafId !== null) {
88 cancelAnimationFrame(state.rafId);
89 }
90 try {
91 if (state.target.hasPointerCapture(pointerId)) {
92 state.target.releasePointerCapture(pointerId);
93 }
94 } catch {
95 // pointer may already be released; harmless.
96 }
97 document.body.style.removeProperty("cursor");
98 document.body.style.removeProperty("user-select");
99 }, []);
100
101 const cancelDrag = useCallback(() => {
102 const state = dragStateRef.current;
103 if (!state) return;
104 releasePointer(state.pointerId);
105 setWidth(state.startWidth);
106 }, [releasePointer]);
107
108 useEffect(() => {
109 window.addEventListener("blur", cancelDrag);
110 return () => {
111 window.removeEventListener("blur", cancelDrag);
112 const state = dragStateRef.current;
113 if (state) releasePointer(state.pointerId);
114 };
115 }, [cancelDrag, releasePointer]);
116
117 const onPointerDown = useCallback(
118 (event: ReactPointerEvent<HTMLElement>) => {
119 if (event.button !== 0 || dragStateRef.current) return;
120 event.preventDefault();
121 event.stopPropagation();
122 const target = event.currentTarget;
123 try {
124 target.setPointerCapture(event.pointerId);
125 } catch {
126 return;
127 }
128 document.body.style.cursor = "col-resize";
129 document.body.style.userSelect = "none";
130 dragStateRef.current = {
131 pointerId: event.pointerId,
132 startX: event.clientX,
133 startWidth: clampedWidth,
134 pending: clampedWidth,
135 rafId: null,
136 target,
137 };
138 },
139 [clampedWidth],
140 );
141
142 const onPointerMove = useCallback(
143 (event: ReactPointerEvent<HTMLElement>) => {
144 const state = dragStateRef.current;
145 if (!state || state.pointerId !== event.pointerId) return;
146 event.preventDefault();
147 const delta = edge === "left" ? state.startX - event.clientX : event.clientX - state.startX;
148 state.pending = clamp(state.startWidth + delta);
149 if (state.rafId !== null) return;
150 state.rafId = requestAnimationFrame(() => {
151 const active = dragStateRef.current;
152 if (!active) return;
153 active.rafId = null;
154 setWidth(active.pending);
155 });
156 },
157 [clamp, edge],
158 );
159
160 const onPointerUp = useCallback(
161 (event: ReactPointerEvent<HTMLElement>) => {
162 const state = dragStateRef.current;
163 if (!state || state.pointerId !== event.pointerId) return;
164 const finalWidth = clamp(state.pending);
165 releasePointer(event.pointerId);
166 // Commit once at drag-end to avoid 60Hz localStorage writes.
167 try {
168 setLocalStorageItem(storageKey, finalWidth, WidthSchema);
169 } catch (error) {
170 console.error("Could not persist panel width.", error);
171 }
172 setWidth(finalWidth);
173 },
174 [clamp, releasePointer, storageKey],
175 );
176
177 const onPointerCancel = useCallback(
178 (event: ReactPointerEvent<HTMLElement>) => {
179 const state = dragStateRef.current;
180 if (!state || state.pointerId !== event.pointerId) return;
181 // Don't persist a cancelled drag; revert to the start width.
182 cancelDrag();
183 },
184 [cancelDrag],
185 );
186
187 return {
188 width: clampedWidth,
189 handlers: {
190 onPointerDown,
191 onPointerMove,
192 onPointerUp,
193 onPointerCancel,
194 onLostPointerCapture: onPointerCancel,
195 },
196 };
197}