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

useResizableWidth.ts

168 lines5.4 KB

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