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

useResizableWidth.ts

102 lines3.8 KB

1import * as Schema from "effect/Schema";
2import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef, useState } from "react";
3​
4import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
5import { useResizeDrag } from "./useResizeDrag";
6​
7const WidthSchema = Schema.Finite;
8​
9/**
10 * Custom property the host element must size itself from.
11 */
12export const RESIZABLE_WIDTH_PROPERTY = "--resizable-width";
13​
14export interface UseResizableWidthOptions {
15 readonly storageKey: string;
16 readonly defaultWidth: number;
17 readonly minWidth: number;
18 readonly maxWidth: number;
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;
27 readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
29​
30/**
31 * Width is read on mount or storage-key changes and persisted on drag-end (not on every rAF tick
32 * — would otherwise be ~60 writes/sec).
33 */
34export function useResizableWidth(options: UseResizableWidthOptions): {
35 readonly width: number;
36 readonly handlers: ResizableWidthHandlers;
37} {
38 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
39​
40 const clamp = (value: number): number => {
41 if (!Number.isFinite(value)) return defaultWidth;
42 return Math.max(minWidth, Math.min(maxWidth, value));
43 };
44​
45 const readWidth = () => {
46 if (typeof window === "undefined") return defaultWidth;
47 try {
48 const stored = getLocalStorageItem(storageKey, WidthSchema);
49 return clamp(stored ?? defaultWidth);
50 } catch (error) {
51 console.error("Could not read persisted panel width.", error);
52 return defaultWidth;
53 }
54 };
55 const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
56 if (widthState.storageKey !== storageKey) {
57 setWidthState({ storageKey, width: readWidth() });
58 }
59​
60 const clampedWidth = clamp(widthState.width);
61 const latestOptions = useRef({ clamp, storageKey, width: clampedWidth });
62 useLayoutEffect(() => {
63 latestOptions.current = { clamp, storageKey, width: clampedWidth };
64 }, [clamp, clampedWidth, storageKey]);
65​
66 const { refresh, ...handlers } = useResizeDrag<HTMLElement>((event) => {
67 const host = event.currentTarget.parentElement;
68 // A collapsible host animates width; live drag writes must not. The host
69 // renders its own transition-duration, so override a property it leaves alone.
70 host?.style.setProperty("transition-property", "none");
71 return {
72 width: clampedWidth,
73 edge,
74 resize(value) {
75 const nextWidth = latestOptions.current.clamp(value);
76 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);
77 return nextWidth;
78 },
79 finish(finalWidth) {
80 setWidthState({ storageKey, width: finalWidth });
81 try {
82 setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
83 } catch (error) {
84 console.error("Could not persist panel width.", error);
85 }
86 },
87 cleanup(committed) {
88 host?.style.removeProperty("transition-property");
89 // React skips the write when the rendered width did not change.
90 if (!committed) {
91 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${latestOptions.current.width}px`);
92 }
93 },
94 };
95 }, storageKey);
96​
97 // Bounds can change mid-drag (sidebar opens, window narrows) and the render
98 // rewrites the committed width, so re-apply the live pointer position.
99 useLayoutEffect(refresh, [clamp, clampedWidth, refresh]);
100​
101 return { width: clampedWidth, handlers };