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

useResizableWidth.ts

111 lines3.9 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.
17 */
18export const RESIZABLE_WIDTH_PROPERTY = "--resizable-width";
19​
20export interface UseResizableWidthOptions {
21 readonly storageKey: string;
22 readonly defaultWidth: number;
23 readonly minWidth: number;
24 readonly maxWidth: number;
25 readonly edge: "left" | "right";
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;
35​
36/**
37 * Width is read on mount or storage-key changes and persisted on drag-end (not on every rAF tick
38 * — would otherwise be ~60 writes/sec).
39 */
40export function useResizableWidth(options: UseResizableWidthOptions): {
41 readonly width: number;
42 readonly handlers: ResizableWidthHandlers;
43} {
44 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
45​
46 const clamp = useCallback(
47 (value: number): number => {
48 if (!Number.isFinite(value)) return defaultWidth;
49 return Math.max(minWidth, Math.min(maxWidth, value));
50 },
51 [defaultWidth, maxWidth, minWidth],
52 );
53​
54 const readWidth = () => {
55 if (typeof window === "undefined") return defaultWidth;
56 try {
57 const stored = getLocalStorageItem(storageKey, WidthSchema);
58 return clamp(stored ?? defaultWidth);
59 } catch (error) {
60 console.error("Could not read persisted panel width.", error);
61 return defaultWidth;
62 }
63 };
64 const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
65 if (widthState.storageKey !== storageKey) {
66 setWidthState({ storageKey, width: readWidth() });
67 }
68​
69 const clampedWidth = clamp(widthState.width);
70 const latestOptions = useRef({ clamp, storageKey, width: clampedWidth });
71 useLayoutEffect(() => {
72 latestOptions.current = { clamp, storageKey, width: clampedWidth };
73 }, [clamp, clampedWidth, storageKey]);
74​
75 const { refresh, ...handlers } = useResizeDrag<HTMLElement>((event) => {
76 const host = event.currentTarget.parentElement;
77 // A collapsible host animates width; live drag writes must not. The host
78 // renders its own transition-duration, so override a property it leaves alone.
79 host?.style.setProperty("transition-property", "none");
80 return {
81 width: clampedWidth,
82 edge,
83 resize(value) {
84 const nextWidth = latestOptions.current.clamp(value);
85 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);
86 return nextWidth;
87 },
88 finish(finalWidth) {
89 setWidthState({ storageKey, width: finalWidth });
90 try {
91 setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
92 } catch (error) {
93 console.error("Could not persist panel width.", error);
94 }
95 },
96 cleanup(committed) {
97 host?.style.removeProperty("transition-property");
98 // React skips the write when the rendered width did not change.
99 if (!committed) {
100 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${latestOptions.current.width}px`);
101 }
102 },
103 };
104 }, storageKey);
105​
106 // Bounds can change mid-drag (sidebar opens, window narrows) and the render
107 // rewrites the committed width, so re-apply the live pointer position.
108 useLayoutEffect(refresh, [clamp, clampedWidth, refresh]);
109​
110 return { width: clampedWidth, handlers };