Open History to see the last commit
1import { useEffect, useState } from "react";
2
3import { type ResizableWidthHandlers, useResizableWidth } from "./useResizableWidth";
4
5export interface PreviewPanelInlineSize {
6 readonly width: number;
7 readonly handlers: ResizableWidthHandlers;
8}
9
10const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
11const PREVIEW_PANEL_MIN_WIDTH = 360;
12/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */
13const PREVIEW_PANEL_MAX_WIDTH_PX = 1400;
14/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */
15const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
16const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
17
18export function usePreviewPanelInlineSize(): PreviewPanelInlineSize {
19 const maxWidth = useViewportClampedMaxWidth();
20 return useResizableWidth({
21 storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
22 defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
23 minWidth: PREVIEW_PANEL_MIN_WIDTH,
24 maxWidth,
25 edge: "left",
26 });
27}
28
29/** Keep the resizable panel's upper bound in sync with the current window. */
30function useViewportClampedMaxWidth(): number {
31 const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
32 useEffect(() => {
33 if (typeof window === "undefined") return;
34 let frame = 0;
35 const onResize = () => {
36 if (frame !== 0) return;
37 frame = window.requestAnimationFrame(() => {
38 frame = 0;
39 setVw(window.innerWidth);
40 });
41 };
42 window.addEventListener("resize", onResize);
43 return () => {
44 window.removeEventListener("resize", onResize);
45 if (frame !== 0) window.cancelAnimationFrame(frame);
46 };
47 }, []);
48 return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION));
49}