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

PreviewPanelShell.tsx

184 lines6.4 KB

1import {
2 type CSSProperties,
3 type ReactNode,
4 type RefObject,
5 useLayoutEffect,
6 useRef,
7 useState,
8} from "react";
9​
10import { isElectron } from "~/env";
11import {
12 type PreviewPanelInlineSize,
13 usePreviewPanelInlineSize,
14} from "~/hooks/usePreviewPanelInlineSize";
15import { RESIZABLE_WIDTH_PROPERTY } from "~/hooks/useResizableWidth";
16import { cn } from "~/lib/utils";
17​
18import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
19​
20export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
21​
22interface PreviewPanelShellProps {
23 mode: PreviewPanelMode;
24 maximized?: boolean;
25 inlineSize?: PreviewPanelInlineSize;
26 open?: boolean;
27 /**
28 * Callers embedding this shell for a different surface (e.g. the pull
29 * requests page) should pass their own key so resizing one panel doesn't
30 * clobber the other's remembered width.
31 */
32 widthStorageKey?: string;
33 defaultWidth?: number;
34 children: ReactNode;
36​
37export function PreviewPanelShell(props: PreviewPanelShellProps) {
38 if (props.inlineSize) {
39 return <PreviewPanelShellFrame {...props} inlineSize={props.inlineSize} />;
40 }
41​
42 return <ResizablePreviewPanelShell {...props} />;
44​
45function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
46 const hostRef = useRef<HTMLDivElement | null>(null);
47 const inlineSize = usePreviewPanelInlineSize(hostRef, {
48 enabled: props.mode === "inline" && !props.maximized,
49 widthStorageKey: props.widthStorageKey,
50 defaultWidth: props.defaultWidth,
51 });
52 return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} hostRef={hostRef} />;
54​
55function PreviewPanelShellFrame(
56 props: PreviewPanelShellProps & {
57 inlineSize: PreviewPanelInlineSize;
58 hostRef?: RefObject<HTMLDivElement | null>;
59 },
60) {
61 const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
62 const isInline = props.mode === "inline";
63 const collapsible = isInline && props.open !== undefined;
64 const open = props.open ?? true;
65 const maximized = props.maximized ?? false;
66 const localHostRef = useRef<HTMLDivElement | null>(null);
67 const hostRef = props.hostRef ?? localHostRef;
68 const returnedFocus = useRef(false);
69 const { width, handlers } = props.inlineSize;
70 // Derive suppression before the layout commits so the browser never creates
71 // a width transition for resize or maximize changes.
72 const [layoutTransition, setLayoutTransition] = useState(() => ({
73 open,
74 width,
75 maximized,
76 suppressed: false,
77 }));
78 if (
79 layoutTransition.open !== open ||
80 layoutTransition.width !== width ||
81 layoutTransition.maximized !== maximized
82 ) {
83 setLayoutTransition({
84 open,
85 width,
86 maximized,
87 suppressed:
88 collapsible &&
89 layoutTransition.open === open &&
90 (layoutTransition.width !== width || layoutTransition.maximized !== maximized),
91 });
92 }
93 const suppressWidthTransition = layoutTransition.suppressed;
94 useLayoutEffect(() => {
95 if (!suppressWidthTransition) return;
96 let restoreFrame = 0;
97 const paintFrame = window.requestAnimationFrame(() => {
98 restoreFrame = window.requestAnimationFrame(() => {
99 setLayoutTransition((current) => ({ ...current, suppressed: false }));
100 });
101 });
102 return () => {
103 window.cancelAnimationFrame(paintFrame);
104 window.cancelAnimationFrame(restoreFrame);
105 };
106 }, [suppressWidthTransition]);
107 useLayoutEffect(() => {
108 const host = hostRef.current;
109 if (!host || !collapsible) return;
110 return () => {
111 if (!host.contains(host.ownerDocument.activeElement) && !returnedFocus.current) return;
112 // The toggle moves when the shell unmounts, after an animation or immediately.
113 // Restore focus at its committed location if removal cleared focus to body.
114 queueMicrotask(() => {
115 if (host.ownerDocument.activeElement === host.ownerDocument.body) {
116 host.ownerDocument.querySelector<HTMLButtonElement>("[data-right-panel-toggle]")?.focus();
117 }
118 });
119 };
120 }, [collapsible, hostRef]);
121 useLayoutEffect(() => {
122 const host = hostRef.current;
123 if (!host) return;
124 const collapsed = collapsible && !open;
125 if (!collapsed) returnedFocus.current = false;
126 // Move focus before making its current owner inert, while the toggle is reachable.
127 if (collapsed && host.contains(host.ownerDocument.activeElement)) {
128 const toggle = host.ownerDocument.querySelector<HTMLButtonElement>(
129 "[data-right-panel-toggle]",
130 );
131 toggle?.focus();
132 returnedFocus.current = toggle !== null && host.ownerDocument.activeElement === toggle;
133 }
134 host.toggleAttribute("inert", collapsed);
135 }, [collapsible, open, hostRef]);
136 return (
137 <div
138 ref={hostRef}
139 className={cn(
140 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
141 isInline
142 ? maximized
143 ? // Maximized, the panel's left edge meets the sidebar's own border
144 // (or the window edge), so a second border would double it.
145 "flex-1"
146 : "shrink-0 border-l border-border"
147 : "w-full",
148 collapsible &&
149 "[[data-panel-animations=true]_&]:transition-[width] [[data-panel-animations=true]_&]:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:ease-out",
150 collapsible && open && "[[data-panel-animations=true]_&]:starting:w-0!",
151 collapsible && !open && "pointer-events-none",
152 )}
153 style={
154 isInline
155 ? ({
156 [RESIZABLE_WIDTH_PROPERTY]: `${width}px`,
157 width: maximized
158 ? "100%"
159 : collapsible && !open
160 ? "0px"
161 : `var(${RESIZABLE_WIDTH_PROPERTY})`,
162 transitionDuration: suppressWidthTransition ? "0ms" : undefined,
163 } as CSSProperties)
164 : undefined
165 }
166 data-preview-panel-mode={props.mode}
167 data-preview-panel-maximized={maximized ? "true" : "false"}
168 >
169 {isInline && !maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
170 <div className={cn("h-full min-h-0 w-full", collapsible && "overflow-clip")}>
171 <div
172 className="flex h-full min-h-0 min-w-0 flex-col"
173 style={
174 collapsible && !maximized
175 ? { width: `calc(var(${RESIZABLE_WIDTH_PROPERTY}) - 1px)` }
176 : undefined
177 }
178 >
179 {props.children}
180 </div>
181 </div>
182 </div>
183 );