Open History to see the last commit
1import {
2 type ReactNode,
3 type RefObject,
4 useEffect,
5 useLayoutEffect,
6 useRef,
7 useState,
8} from "react";
9
10import { isElectron } from "~/env";
11import { useResizableWidth } from "~/hooks/useResizableWidth";
12import { cn } from "~/lib/utils";
13
14import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
15
16export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
17
18const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
19const PREVIEW_PANEL_MIN_WIDTH = 360;
20/**
21 * Upper bound as a fraction of the viewport; only binds on wide screens.
22 * On narrow windows the container clamp below is what preserves the
23 * sibling column's space.
24 */
25const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
26const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
27/**
28 * Width reserved for the sibling column (chat, pull-request list) sharing the
29 * panel's flex row. The viewport fraction alone is not enough: the app
30 * sidebar sits outside the row, so on narrow windows (any MacBook, even
31 * fullscreen) the remaining 30% of the viewport minus the sidebar left the
32 * sibling below its usable width and the composer overflowed.
33 */
34const SIBLING_COLUMN_MIN_WIDTH = 360;
35
36export function getPreviewPanelMaxWidth(viewportWidth: number, containerWidth?: number): number {
37 const fractionCap = Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
38 const containerCap =
39 containerWidth === undefined ? Infinity : Math.floor(containerWidth) - SIBLING_COLUMN_MIN_WIDTH;
40 // Never below the panel's own minimum: when the row cannot fit both
41 // columns' minimums the sibling yields, and useResizableWidth's clamp
42 // must not see max < min (it would resolve the inversion to min and,
43 // via drag-end persistence, overwrite the user's stored width).
44 return Math.max(PREVIEW_PANEL_MIN_WIDTH, Math.min(fractionCap, containerCap));
45}
46
47/**
48 * Shell for the preview panel. In inline mode the panel is user-resizable
49 * via a drag handle on the left edge; width persists per browser. In
50 * sheet/sidebar modes the parent owns the size.
51 */
52export function PreviewPanelShell(props: {
53 mode: PreviewPanelMode;
54 maximized?: boolean;
55 open?: boolean;
56 /**
57 * Overrides the localStorage key used to persist the panel width. Callers
58 * embedding this shell for a different surface (e.g. the pull requests
59 * page) should pass their own key so resizing one panel doesn't clobber
60 * the other's remembered width.
61 */
62 widthStorageKey?: string;
63 /** Overrides the initial width (px) before the user has resized the panel. */
64 defaultWidth?: number;
65 children: ReactNode;
66}) {
67 const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
68 const isInline = props.mode === "inline";
69 const collapsible = isInline && props.open !== undefined;
70 const open = props.open ?? true;
71 const hostRef = useRef<HTMLDivElement | null>(null);
72 // Only inline non-maximized mode applies `width`/`maxWidth`; skip the
73 // container measurement (and its re-renders) everywhere else.
74 const maxWidth = useClampedMaxWidth(hostRef, isInline && !props.maximized);
75 const { width, handlers } = useResizableWidth({
76 storageKey: props.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
77 defaultWidth: props.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
78 minWidth: PREVIEW_PANEL_MIN_WIDTH,
79 maxWidth,
80 edge: "left",
81 });
82 const previousLayoutRef = useRef({ open, width });
83 useLayoutEffect(() => {
84 const previous = previousLayoutRef.current;
85 previousLayoutRef.current = { open, width };
86 if (!collapsible || previous.open !== open || previous.width === width) return;
87 const host = hostRef.current;
88 if (!host?.closest("[data-panel-animations=true]")) return;
89 host.style.setProperty("transition-duration", "0ms");
90 let restoreFrame = 0;
91 const paintFrame = window.requestAnimationFrame(() => {
92 restoreFrame = window.requestAnimationFrame(() => {
93 host.style.removeProperty("transition-duration");
94 });
95 });
96 return () => {
97 window.cancelAnimationFrame(paintFrame);
98 window.cancelAnimationFrame(restoreFrame);
99 host.style.removeProperty("transition-duration");
100 };
101 }, [collapsible, open, width]);
102 return (
103 <div
104 ref={hostRef}
105 className={cn(
106 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
107 isInline
108 ? props.maximized
109 ? "flex-1 border-l border-border"
110 : "shrink-0 border-l border-border"
111 : "w-full",
112 collapsible &&
113 "[[data-panel-animations=true]_&]:transition-[width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
114 collapsible && open && "[[data-panel-animations=true]_&]:starting:w-0!",
115 collapsible && !open && "pointer-events-none",
116 )}
117 style={
118 isInline
119 ? { width: props.maximized ? "100%" : collapsible && !open ? "0px" : `${width}px` }
120 : undefined
121 }
122 data-preview-panel-mode={props.mode}
123 data-preview-panel-maximized={props.maximized ? "true" : "false"}
124 >
125 {isInline && !props.maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
126 <div className={cn("h-full min-h-0 w-full", collapsible && "overflow-clip")}>
127 <div
128 className="flex h-full min-h-0 min-w-0 flex-col"
129 style={collapsible && !props.maximized ? { width: `calc(${width}px - 1px)` } : undefined}
130 >
131 {useDragRegion ? <div className="electron-drag-region h-0 w-full" aria-hidden /> : null}
132 {props.children}
133 </div>
134 </div>
135 </div>
136 );
137}
138
139/**
140 * Track viewport and flex-row widths to derive an upper bound for the panel.
141 * Resize-aware so dragging the OS window narrower (or expanding the app
142 * sidebar) re-clamps the stored width on the next render (the hook's clamp
143 * picks this up automatically). The row is observed rather than the panel
144 * itself because the panel competes with its sibling column for row space.
145 * Row measurement only runs when `enabled`; modes without a resize handle
146 * never apply the resulting width, so they skip the observer entirely.
147 */
148function useClampedMaxWidth(hostRef: RefObject<HTMLDivElement | null>, enabled: boolean): number {
149 const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
150 const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
151 useEffect(() => {
152 if (typeof window === "undefined") return;
153 let frame = 0;
154 const onResize = () => {
155 // Coalesce rapid resize events into one rAF tick.
156 if (frame !== 0) return;
157 frame = window.requestAnimationFrame(() => {
158 frame = 0;
159 setVw(window.innerWidth);
160 });
161 };
162 window.addEventListener("resize", onResize);
163 return () => {
164 window.removeEventListener("resize", onResize);
165 if (frame !== 0) window.cancelAnimationFrame(frame);
166 };
167 }, []);
168 useLayoutEffect(() => {
169 if (!enabled) return;
170 const parent = hostRef.current?.parentElement;
171 if (!parent) return;
172 // Measure before first paint: the persisted width must be clamped
173 // against the row on the initial render, not one observer tick later
174 // (the panel would flash over-wide on every mount). clientWidth is
175 // integral, so sub-pixel resize deltas bail out of re-rendering.
176 const measure = () => {
177 setContainerWidth(parent.clientWidth);
178 };
179 measure();
180 if (typeof ResizeObserver === "undefined") return;
181 const observer = new ResizeObserver(measure);
182 observer.observe(parent);
183 return () => {
184 observer.disconnect();
185 };
186 }, [hostRef, enabled]);
187 return getPreviewPanelMaxWidth(vw, containerWidth);
188}