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

useResizableWidth.ts

127 lines4.8 KB

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​
15/**
16 * Custom property the host element must size itself from. The drag handle sits
17 * directly inside the host, and a drag writes this property on it each frame.
18 */
19export const RESIZABLE_WIDTH_PROPERTY = "--resizable-width";
20​
21export interface UseResizableWidthOptions {
22 /** localStorage key the persisted width is stored under. */
23 readonly storageKey: string;
24 readonly defaultWidth: number;
25 readonly minWidth: number;
26 readonly maxWidth: number;
27 /**
28 * Which edge of the host element carries the drag handle:
29 * - "left" → panel grows leftward (right-anchored panels)
30 * - "right" → panel grows rightward (left-anchored panels)
31 */
32 readonly edge: "left" | "right";
34​
35export interface ResizableWidthHandlers {
36 readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
37 readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
38 readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
39 readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
40 readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
42​
43/**
44 * Width state for a side-anchored panel resized via a drag handle on the
45 * specified edge. Width is read on mount or storage-key changes and persisted on
46 * drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
47 *
48 * During a drag the hook writes `RESIZABLE_WIDTH_PROPERTY` on the handle's
49 * parent, so the panel follows the cursor in the same frame without
50 * re-rendering the owner. `width` state and localStorage commit once when the
51 * user lifts the pointer or the drag is interrupted.
52 */
53export function useResizableWidth(options: UseResizableWidthOptions): {
54 readonly width: number;
55 readonly handlers: ResizableWidthHandlers;
56} {
57 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
58​
59 const clamp = useCallback(
60 (value: number): number => {
61 if (!Number.isFinite(value)) return defaultWidth;
62 return Math.max(minWidth, Math.min(maxWidth, value));
63 },
64 [defaultWidth, maxWidth, minWidth],
65 );
66​
67 // No cross-tab subscription: panel width is per-window state.
68 const readWidth = () => {
69 if (typeof window === "undefined") return defaultWidth;
70 try {
71 const stored = getLocalStorageItem(storageKey, WidthSchema);
72 return clamp(stored ?? defaultWidth);
73 } catch (error) {
74 console.error("Could not read persisted panel width.", error);
75 return defaultWidth;
76 }
77 };
78 const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
79 // Panels stay mounted across threads; restore the destination width before paint.
80 if (widthState.storageKey !== storageKey) {
81 setWidthState({ storageKey, width: readWidth() });
82 }
83​
84 const clampedWidth = clamp(widthState.width);
85 const latestOptions = useRef({ clamp, storageKey, width: clampedWidth });
86 useLayoutEffect(() => {
87 latestOptions.current = { clamp, storageKey, width: clampedWidth };
88 }, [clamp, clampedWidth, storageKey]);
89​
90 const { refresh, ...handlers } = useResizeDrag<HTMLElement>((event) => {
91 const host = event.currentTarget.parentElement;
92 // A collapsible host animates width; live drag writes must not. The host
93 // renders its own transition-duration, so override a property it leaves alone.
94 host?.style.setProperty("transition-property", "none");
95 return {
96 width: clampedWidth,
97 edge,
98 resize(value) {
99 const nextWidth = latestOptions.current.clamp(value);
100 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);
101 return nextWidth;
102 },
103 finish(finalWidth) {
104 setWidthState({ storageKey, width: finalWidth });
105 // Commit once at drag-end to avoid 60Hz localStorage writes.
106 try {
107 setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
108 } catch (error) {
109 console.error("Could not persist panel width.", error);
110 }
111 },
112 cleanup(committed) {
113 host?.style.removeProperty("transition-property");
114 // React skips the write when the rendered width did not change.
115 if (!committed) {
116 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${latestOptions.current.width}px`);
117 }
118 },
119 };
120 }, storageKey);
121​
122 // Bounds can change mid-drag (sidebar opens, window narrows) and the render
123 // rewrites the committed width, so re-apply the live pointer position.
124 useLayoutEffect(refresh, [clamp, clampedWidth, refresh]);
125​
126 return { width: clampedWidth, handlers };