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