Files
t3code/apps/web/src/hooks/useResizableWidth.ts
T

106 lines
3.6 KiB
TypeScript

import * as Schema from "effect/Schema";
import {
type PointerEvent as ReactPointerEvent,
useCallback,
useLayoutEffect,
useRef,
useState,
} from "react";
import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
import { useResizeDrag } from "./useResizeDrag";
const WidthSchema = Schema.Finite;
export interface UseResizableWidthOptions {
/** localStorage key the persisted width is stored under. */
readonly storageKey: string;
readonly defaultWidth: number;
readonly minWidth: number;
readonly maxWidth: number;
/**
* Which edge of the host element carries the drag handle:
* - "left" → panel grows leftward (right-anchored panels)
* - "right" → panel grows rightward (left-anchored panels)
*/
readonly edge: "left" | "right";
}
export interface ResizableWidthHandlers {
readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;
}
/**
* Width state for a side-anchored panel resized via a drag handle on the
* specified edge. Width is read on mount or storage-key changes and persisted on
* drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
*
* The hook updates an internal `width` state during drag (so the panel
* follows the cursor live) and only commits to localStorage when the user
* lifts the pointer or the drag is interrupted.
*/
export function useResizableWidth(options: UseResizableWidthOptions): {
readonly width: number;
readonly handlers: ResizableWidthHandlers;
} {
const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
const clamp = useCallback(
(value: number): number => {
if (!Number.isFinite(value)) return defaultWidth;
return Math.max(minWidth, Math.min(maxWidth, value));
},
[defaultWidth, maxWidth, minWidth],
);
// No cross-tab subscription: panel width is per-window state.
const readWidth = () => {
if (typeof window === "undefined") return defaultWidth;
try {
const stored = getLocalStorageItem(storageKey, WidthSchema);
return clamp(stored ?? defaultWidth);
} catch (error) {
console.error("Could not read persisted panel width.", error);
return defaultWidth;
}
};
const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));
// Panels stay mounted across threads; restore the destination width before paint.
if (widthState.storageKey !== storageKey) {
setWidthState({ storageKey, width: readWidth() });
}
const clampedWidth = clamp(widthState.width);
const latestOptions = useRef({ clamp, storageKey });
useLayoutEffect(() => {
latestOptions.current = { clamp, storageKey };
}, [clamp, storageKey]);
const handlers = useResizeDrag<HTMLElement>(
() => ({
width: clampedWidth,
edge,
resize(value) {
const nextWidth = latestOptions.current.clamp(value);
setWidthState({ storageKey, width: nextWidth });
return nextWidth;
},
finish(finalWidth) {
// Commit once at drag-end to avoid 60Hz localStorage writes.
try {
setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
} catch (error) {
console.error("Could not persist panel width.", error);
}
},
}),
storageKey,
);
return { width: clampedWidth, handlers };
}