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 maximized = props.maximized ?? false;
72 const hostRef = useRef<HTMLDivElement | null>(null);
73 // Only inline non-maximized mode applies `width`/`maxWidth`; skip the
74 // container measurement (and its re-renders) everywhere else.
75 const maxWidth = useClampedMaxWidth(hostRef, isInline && !maximized);
76 const { width, handlers } = useResizableWidth({
77 storageKey: props.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
78 defaultWidth: props.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
79 minWidth: PREVIEW_PANEL_MIN_WIDTH,
80 maxWidth,
81 edge: "left",
82 });
83 // Derive suppression before the layout commits so the browser never creates
84 // a width transition for resize or maximize changes.
85 const [layoutTransition, setLayoutTransition] = useState(() => ({
86 open,
87 width,
88 maximized,
89 suppressed: false,
90 }));
91 if (
92 layoutTransition.open !== open ||
93 layoutTransition.width !== width ||
94 layoutTransition.maximized !== maximized
95 ) {
96 setLayoutTransition({
97 open,
98 width,
99 maximized,
100 suppressed:
101 collapsible &&
102 layoutTransition.open === open &&
103 (layoutTransition.width !== width || layoutTransition.maximized !== maximized),
104 });
105 }
106 const suppressWidthTransition = layoutTransition.suppressed;
107 useLayoutEffect(() => {
108 if (!suppressWidthTransition) return;
109 let restoreFrame = 0;
110 const paintFrame = window.requestAnimationFrame(() => {
111 restoreFrame = window.requestAnimationFrame(() => {
112 setLayoutTransition((current) => ({ ...current, suppressed: false }));
113 });
114 });
115 return () => {
116 window.cancelAnimationFrame(paintFrame);
117 window.cancelAnimationFrame(restoreFrame);
118 };
119 }, [suppressWidthTransition]);
120 return (
121 <div
122 ref={hostRef}
123 className={cn(
124 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
125 isInline
126 ? maximized
127 ? "flex-1 border-l border-border"
128 : "shrink-0 border-l border-border"
129 : "w-full",
130 collapsible &&
131 "[[data-panel-animations=true]_&]:transition-[width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
132 collapsible && open && "[[data-panel-animations=true]_&]:starting:w-0!",
133 collapsible && !open && "pointer-events-none",
134 )}
135 style={
136 isInline
137 ? {
138 width: maximized ? "100%" : collapsible && !open ? "0px" : `${width}px`,
139 transitionDuration: suppressWidthTransition ? "0ms" : undefined,
140 }
141 : undefined
142 }
143 data-preview-panel-mode={props.mode}
144 data-preview-panel-maximized={maximized ? "true" : "false"}
145 >
146 {isInline && !maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
147 <div className={cn("h-full min-h-0 w-full", collapsible && "overflow-clip")}>
148 <div
149 className="flex h-full min-h-0 min-w-0 flex-col"
150 style={collapsible && !maximized ? { width: `calc(${width}px - 1px)` } : undefined}
151 >
152 {useDragRegion ? <div className="electron-drag-region h-0 w-full" aria-hidden /> : null}
153 {props.children}
154 </div>
155 </div>
156 </div>
157 );
158}
159
160/**
161 * Track viewport and flex-row widths to derive an upper bound for the panel.
162 * Resize-aware so dragging the OS window narrower (or expanding the app
163 * sidebar) re-clamps the stored width on the next render (the hook's clamp
164 * picks this up automatically). The row is observed rather than the panel
165 * itself because the panel competes with its sibling column for row space.
166 * Row measurement only runs when `enabled`; modes without a resize handle
167 * never apply the resulting width, so they skip the observer entirely.
168 */
169function useClampedMaxWidth(hostRef: RefObject<HTMLDivElement | null>, enabled: boolean): number {
170 const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
171 const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
172 useEffect(() => {
173 if (typeof window === "undefined") return;
174 let frame = 0;
175 const onResize = () => {
176 // Coalesce rapid resize events into one rAF tick.
177 if (frame !== 0) return;
178 frame = window.requestAnimationFrame(() => {
179 frame = 0;
180 setVw(window.innerWidth);
181 });
182 };
183 window.addEventListener("resize", onResize);
184 return () => {
185 window.removeEventListener("resize", onResize);
186 if (frame !== 0) window.cancelAnimationFrame(frame);
187 };
188 }, []);
189 useLayoutEffect(() => {
190 if (!enabled) return;
191 const parent = hostRef.current?.parentElement;
192 if (!parent) return;
193 // Measure before first paint: the persisted width must be clamped
194 // against the row on the initial render, not one observer tick later
195 // (the panel would flash over-wide on every mount). clientWidth is
196 // integral, so sub-pixel resize deltas bail out of re-rendering.
197 const measure = () => {
198 setContainerWidth(parent.clientWidth);
199 };
200 measure();
201 if (typeof ResizeObserver === "undefined") return;
202 const observer = new ResizeObserver(measure);
203 observer.observe(parent);
204 return () => {
205 observer.disconnect();
206 };
207 }, [hostRef, enabled]);
208 return getPreviewPanelMaxWidth(vw, containerWidth);
209}