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