Open History to see the last commit
1import * as Schema from "effect/Schema";
2import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useState } from "react";
3
4import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
5import { useResizeDrag } from "./useResizeDrag";
6
7const WidthSchema = Schema.Finite;
8
9/** The host must size itself from this custom property. */
10export const RESIZABLE_WIDTH_PROPERTY = "--resizable-width";
11
12export interface UseResizableWidthOptions {
13 readonly storageKey: string;
14 readonly defaultWidth: number;
15 readonly minWidth: number;
16 readonly maxWidth: number;
17 readonly edge: "left" | "right";
18}
19
20export interface ResizableWidthHandlers {
21 readonly ref: (node: HTMLElement | null) => (() => void) | undefined;
22 readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
23 readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
24 readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
25 readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
26 readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
27}
28
29/** Persist on drag end to avoid a storage write on every animation frame. */
30export function useResizableWidth(options: UseResizableWidthOptions): {
31 readonly width: number;
32 readonly setWidth: (width: number) => void;
33 readonly handlers: ResizableWidthHandlers;
34} {
35 const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
36
37 const clamp = (value: number): number => {
38 if (!Number.isFinite(value)) return defaultWidth;
39 return Math.max(minWidth, Math.min(maxWidth, value));
40 };
41
42 const readWidth = () => {
43 if (typeof window === "undefined") return defaultWidth;
44 try {
45 const stored = getLocalStorageItem(storageKey, WidthSchema);
46 return clamp(stored ?? defaultWidth);
47 } catch (error) {
48 console.error("Could not read persisted panel width.", error);
49 return defaultWidth;
50 }
51 };
52 const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
53 if (widthState.storageKey !== storageKey) {
54 setWidthState({ storageKey, width: readWidth() });
55 }
56
57 const clampedWidth = clamp(widthState.width);
58
59 const commitWidth = (nextStorageKey: string, nextWidth: number) => {
60 // Resizing remains usable for this session when browser storage is unavailable.
61 setWidthState({ storageKey: nextStorageKey, width: nextWidth });
62 try {
63 setLocalStorageItem(nextStorageKey, nextWidth, WidthSchema);
64 } catch (error) {
65 console.error("Could not persist panel width.", error);
66 }
67 };
68
69 const drag = useResizeDrag<HTMLElement>((event) => {
70 const host = event.currentTarget.parentElement;
71 // Disable drag transitions through transition-property; the host renders transition-duration.
72 host?.style.setProperty("transition-property", "none");
73 // The drag commits to the key and width it started from, even if the panel
74 // switches keys before the pointer is released.
75 const startStorageKey = storageKey;
76 const startWidth = clampedWidth;
77 return {
78 width: startWidth,
79 edge,
80 bounds: { min: minWidth, max: maxWidth },
81 resize(nextWidth) {
82 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);
83 return nextWidth;
84 },
85 finish(finalWidth) {
86 commitWidth(startStorageKey, finalWidth);
87 },
88 cleanup(committed) {
89 host?.style.removeProperty("transition-property");
90 if (!committed) host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${startWidth}px`);
91 },
92 };
93 });
94
95 // Bounds can change mid-drag (sidebar opens, window narrows), and the render
96 // that carries them rewrites the committed width, so re-apply the live pointer position.
97 const { refresh } = drag;
98 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reapplies the live drag pointer position to the DOM before paint when the bounds change
99 useLayoutEffect(() => refresh({ min: minWidth, max: maxWidth }), [refresh, minWidth, maxWidth]);
100
101 return {
102 width: clampedWidth,
103 setWidth: (value) => commitWidth(storageKey, clamp(value)),
104 handlers: {
105 ref: drag.ref,
106 onPointerDown: drag.onPointerDown,
107 onPointerMove: drag.onPointerMove,
108 onPointerUp: drag.onPointerUp,
109 onPointerCancel: drag.onPointerCancel,
110 onLostPointerCapture: drag.onLostPointerCapture,
111 },
112 };
113}