Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewPanelShell.tsx

151 lines6.0 KB

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));
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 /**
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 useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
67 const isInline = props.mode === "inline";
68 const hostRef = useRef<HTMLDivElement | null>(null);
69 // Only inline non-maximized mode applies `width`/`maxWidth`; skip the
70 // container measurement (and its re-renders) everywhere else.
71 const maxWidth = useClampedMaxWidth(hostRef, isInline && !props.maximized);
72 const { width, handlers } = useResizableWidth({
73 storageKey: props.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
74 defaultWidth: props.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
75 minWidth: PREVIEW_PANEL_MIN_WIDTH,
76 maxWidth,
77 edge: "left",
78 });
79​
80 return (
81 <div
82 ref={hostRef}
83 className={cn(
84 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
85 isInline
86 ? props.maximized
87 ? "flex-1 border-l border-border"
88 : "shrink-0 border-l border-border"
89 : "w-full",
90 )}
91 style={isInline && !props.maximized ? { width: `${width}px` } : undefined}
92 data-preview-panel-mode={props.mode}
93 data-preview-panel-maximized={props.maximized ? "true" : "false"}
94 >
95 {isInline && !props.maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
96 {useDragRegion ? <div className="electron-drag-region h-0 w-full" aria-hidden /> : null}
97 {props.children}
98 </div>
99 );
101​
102/**
103 * Track viewport and flex-row widths to derive an upper bound for the panel.
104 * Resize-aware so dragging the OS window narrower (or expanding the app
105 * sidebar) re-clamps the stored width on the next render (the hook's clamp
106 * picks this up automatically). The row is observed rather than the panel
107 * itself because the panel competes with its sibling column for row space.
108 * Row measurement only runs when `enabled`; modes without a resize handle
109 * never apply the resulting width, so they skip the observer entirely.
110 */
111function useClampedMaxWidth(hostRef: RefObject<HTMLDivElement | null>, enabled: boolean): number {
112 const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
113 const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
114 useEffect(() => {
115 if (typeof window === "undefined") return;
116 let frame = 0;
117 const onResize = () => {
118 // Coalesce rapid resize events into one rAF tick.
119 if (frame !== 0) return;
120 frame = window.requestAnimationFrame(() => {
121 frame = 0;
122 setVw(window.innerWidth);
123 });
124 };
125 window.addEventListener("resize", onResize);
126 return () => {
127 window.removeEventListener("resize", onResize);
128 if (frame !== 0) window.cancelAnimationFrame(frame);
129 };
130 }, []);
131 useLayoutEffect(() => {
132 if (!enabled) return;
133 const parent = hostRef.current?.parentElement;
134 if (!parent) return;
135 // Measure before first paint: the persisted width must be clamped
136 // against the row on the initial render, not one observer tick later
137 // (the panel would flash over-wide on every mount). clientWidth is
138 // integral, so sub-pixel resize deltas bail out of re-rendering.
139 const measure = () => {
140 setContainerWidth(parent.clientWidth);
141 };
142 measure();
143 if (typeof ResizeObserver === "undefined") return;
144 const observer = new ResizeObserver(measure);
145 observer.observe(parent);
146 return () => {
147 observer.disconnect();
148 };
149 }, [hostRef, enabled]);
150 return getPreviewPanelMaxWidth(vw, containerWidth);