Open History to see the last commit
1import * as Schema from "effect/Schema";
2import {
3 type PointerEvent as ReactPointerEvent,
4 useCallback,
5 useLayoutEffect,
6 useRef,
7 useState,
8} from "react";
9
10import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
11import { useResizeDrag } from "./useResizeDrag";
12
13const WidthSchema = Schema.Finite;
14
15export interface UseResizableWidthOptions {
16 /** localStorage key the persisted width is stored under. */
17 readonly storageKey: string;
18 readonly defaultWidth: number;
19 readonly minWidth: number;
20 readonly maxWidth: number;
21 /**
22 * Which edge of the host element carries the drag handle:
23 * - "left" → panel grows leftward (right-anchored panels)
24 * - "right" → panel grows rightward (left-anchored panels)
25 */
26 readonly edge: "left" | "right";
27}
28
29export interface ResizableWidthHandlers {
30 readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
31 readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
32 readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
33 readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
34 readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
35}
36
37/**
38 * Width state for a side-anchored panel resized via a drag handle on the
39 * specified edge. Width is read on mount or storage-key changes and persisted on
40 * drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
41 *
42 * The hook updates an internal `width` state during drag (so the panel
43 * follows the cursor live) and only commits to localStorage when the user
44 * lifts the pointer or the drag is interrupted.
45 */
46export function useResizableWidth(options: UseResizableWidthOptions): {
47 readonly width: number;
48 readonly handlers: ResizableWidthHandlers;
49} {
50 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
51
52 const clamp = useCallback(
53 (value: number): number => {
54 if (!Number.isFinite(value)) return defaultWidth;
55 return Math.max(minWidth, Math.min(maxWidth, value));
56 },
57 [defaultWidth, maxWidth, minWidth],
58 );
59
60 // No cross-tab subscription: panel width is per-window state.
61 const readWidth = () => {
62 if (typeof window === "undefined") return defaultWidth;
63 try {
64 const stored = getLocalStorageItem(storageKey, WidthSchema);
65 return clamp(stored ?? defaultWidth);
66 } catch (error) {
67 console.error("Could not read persisted panel width.", error);
68 return defaultWidth;
69 }
70 };
71 const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
72 // Panels stay mounted across threads; restore the destination width before paint.
73 if (widthState.storageKey !== storageKey) {
74 setWidthState({ storageKey, width: readWidth() });
75 }
76
77 const clampedWidth = clamp(widthState.width);
78 const latestOptions = useRef({ clamp, storageKey });
79 useLayoutEffect(() => {
80 latestOptions.current = { clamp, storageKey };
81 }, [clamp, storageKey]);
82
83 const handlers = useResizeDrag<HTMLElement>(
84 () => ({
85 width: clampedWidth,
86 edge,
87 resize(value) {
88 const nextWidth = latestOptions.current.clamp(value);
89 setWidthState({ storageKey, width: nextWidth });
90 return nextWidth;
91 },
92 finish(finalWidth) {
93 // Commit once at drag-end to avoid 60Hz localStorage writes.
94 try {
95 setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
96 } catch (error) {
97 console.error("Could not persist panel width.", error);
98 }
99 },
100 }),
101 storageKey,
102 );
103
104 return { width: clampedWidth, handlers };
105}