Open History to see the last commit
1import { useGT } from "gt-react";
2import {
3 type CSSProperties,
4 type FocusEvent,
5 type MouseEventHandler,
6 type ReactNode,
7 useLayoutEffect,
8 useRef,
9 useState,
10} from "react";
11import {
12 type PreviewPanelInlineSize,
13 usePreviewPanelInlineSize,
14} from "~/hooks/usePreviewPanelInlineSize";
15import { RESIZABLE_WIDTH_PROPERTY } from "~/hooks/useResizableWidth";
16import { canReturnFocusTo, workspaceAreaProps } from "../../lib/workspaceFocus";
17import { cn } from "~/lib/utils";
18
19import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
20
21export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded";
22
23interface PreviewPanelShellProps {
24 workspaceArea?: boolean;
25 workspaceFocusKey?: string;
26 workspaceLabel?: string;
27 mode: PreviewPanelMode;
28 maximized?: boolean;
29 inlineSize?: PreviewPanelInlineSize;
30 open?: boolean;
31 /** Resolve the return target after unmount, when controls hidden by the panel are visible again. */
32 restoreFocusOnUnmount?: (origin: HTMLElement | null) => HTMLElement | null;
33 /** Use a distinct key per surface to keep remembered widths independent. */
34 widthStorageKey?: string;
35 defaultWidth?: number;
36 onMouseDown?: MouseEventHandler<HTMLDivElement>;
37 onMouseUp?: MouseEventHandler<HTMLDivElement>;
38 children: ReactNode;
39}
40
41export function PreviewPanelShell(props: PreviewPanelShellProps) {
42 if (props.inlineSize) {
43 return <PreviewPanelShellFrame {...props} inlineSize={props.inlineSize} />;
44 }
45
46 return <ResizablePreviewPanelShell {...props} />;
47}
48
49function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
50 const inlineSize = usePreviewPanelInlineSize({
51 enabled: props.mode === "inline" && !props.maximized,
52 widthStorageKey: props.widthStorageKey,
53 defaultWidth: props.defaultWidth,
54 });
55 return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} />;
56}
57
58// Prefers the element focus entered the panel from, falling back to the panel toggle.
59function returnFocus(host: HTMLElement, origin: HTMLElement | null) {
60 const { ownerDocument } = host;
61 // focus() is a no-op on a disabled origin, so activeElement says whether it took.
62 if (origin?.isConnected && !host.contains(origin) && canReturnFocusTo(origin)) {
63 origin.focus({ preventScroll: true });
64 if (ownerDocument.activeElement === origin) return true;
65 }
66 const toggle = ownerDocument.querySelector<HTMLButtonElement>("[data-right-panel-toggle]");
67 toggle?.focus();
68 return toggle !== null && ownerDocument.activeElement === toggle;
69}
70
71// A pointer press on the toggle takes focus from the panel before its click closes it, and
72// unmounting the panel moves the toggle, which drops that focus to the body.
73function holdsPanelFocus(host: HTMLElement, pressedToggle: HTMLElement | null) {
74 const { activeElement, body } = host.ownerDocument;
75 return (
76 host.contains(activeElement) ||
77 (pressedToggle !== null && (activeElement === pressedToggle || activeElement === body))
78 );
79}
80
81function PreviewPanelShellFrame(
82 props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
83) {
84 const gt = useGT();
85 const panelArea = workspaceAreaProps("panel", 4, props.workspaceLabel ?? gt`Workspace panel`);
86 const isInline = props.mode === "inline";
87 const collapsible = isInline && props.open !== undefined;
88 const restoreFocusOnUnmount = props.restoreFocusOnUnmount ?? collapsible;
89 const open = props.open ?? true;
90 const maximized = props.maximized ?? false;
91 const hostRef = useRef<HTMLDivElement | null>(null);
92 const returnedFocus = useRef(false);
93 const focusOrigin = useRef<HTMLElement | null>(null);
94 const lastBlurred = useRef<EventTarget | null>(null);
95 const pressedToggle = useRef<HTMLElement | null>(null);
96 const { width, handlers, observeRow } = props.inlineSize;
97 // Width animates only for an open or close. Any other width change disables
98 // the transition in the same commit that changes the width, so the browser
99 // never starts one; the next open or close re-enables it in its own commit,
100 // so nothing waits for a paint.
101 const [widthTransition, setWidthTransition] = useState(() => ({
102 open,
103 width,
104 maximized,
105 enabled: true,
106 }));
107 if (
108 widthTransition.open !== open ||
109 widthTransition.width !== width ||
110 widthTransition.maximized !== maximized
111 ) {
112 setWidthTransition({
113 open,
114 width,
115 maximized,
116 enabled: widthTransition.open !== open,
117 });
118 }
119 const suppressWidthTransition = collapsible && !widthTransition.enabled;
120 const attachHost = (host: HTMLDivElement) => {
121 hostRef.current = host;
122 const stopObservingRow = observeRow(host);
123 return () => {
124 hostRef.current = null;
125 stopObservingRow();
126 };
127 };
128 // React focus events, unlike a listener added in attachHost, also see content that focuses
129 // itself while mounting (a terminal does, from a ref that attaches before the host's).
130 // Focus moving within the panel, portalled menus included, first blurs an element of it.
131 const rememberFocusOrigin = (event: FocusEvent<HTMLDivElement>) => {
132 const from = event.relatedTarget;
133 if (from === null || from === lastBlurred.current) return;
134 focusOrigin.current = from instanceof HTMLElement ? from : null;
135 };
136 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- on unmount, returns DOM focus to where it came from if removal dropped it on the body
137 useLayoutEffect(() => {
138 const host = hostRef.current;
139 if (!host || !restoreFocusOnUnmount) return;
140 return () => {
141 const heldFocus = holdsPanelFocus(host, pressedToggle.current);
142 if (!heldFocus && !returnedFocus.current) return;
143 const toggle = heldFocus ? pressedToggle.current : null;
144 const origin = focusOrigin.current;
145 // Unmount moves the toggle; restore focus at its committed location if removal sent focus to body.
146 queueMicrotask(() => {
147 const active = host.ownerDocument.activeElement;
148 if (active === host.ownerDocument.body || (toggle !== null && active === toggle)) {
149 returnFocus(
150 host,
151 typeof restoreFocusOnUnmount === "function" ? restoreFocusOnUnmount(origin) : origin,
152 );
153 }
154 });
155 };
156 }, [restoreFocusOnUnmount, hostRef]);
157 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves focus out of the host and sets inert on it before a collapse paints
158 useLayoutEffect(() => {
159 const host = hostRef.current;
160 if (!host) return;
161 const collapsed = collapsible && !open;
162 if (!collapsed) returnedFocus.current = false;
163 // Move focus before making its current owner inert, while the toggle is reachable.
164 if (collapsed && holdsPanelFocus(host, pressedToggle.current)) {
165 returnedFocus.current = returnFocus(host, focusOrigin.current);
166 }
167 // An origin and a press belong to one open; the next one records its own.
168 if (collapsed) {
169 focusOrigin.current = null;
170 pressedToggle.current = null;
171 }
172 host.toggleAttribute("inert", collapsed);
173 }, [collapsible, open, hostRef]);
174 return (
175 <div
176 ref={attachHost}
177 onFocus={rememberFocusOrigin}
178 onBlur={(event) => {
179 lastBlurred.current = event.target;
180 const to = event.relatedTarget;
181 // :active is set by the press itself, so keyboard focus on the toggle keeps it.
182 pressedToggle.current =
183 to instanceof HTMLElement && to.matches("[data-right-panel-toggle]:active") ? to : null;
184 }}
185 {...(props.workspaceArea ? panelArea : {})}
186 data-workspace-focus-key={props.workspaceFocusKey}
187 data-workspace-unavailable={collapsible && !open ? "true" : undefined}
188 onMouseDown={props.onMouseDown}
189 onMouseUp={props.onMouseUp}
190 className={cn(
191 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
192 isInline
193 ? maximized
194 ? // Maximizing meets the sidebar border or window edge; omit the duplicate border.
195 "flex-1"
196 : "shrink-0 border-l border-border"
197 : "w-full",
198 collapsible &&
199 "[[data-panel-animations=true]_&]:transition-[width] [[data-panel-animations=true]_&]:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:ease-out",
200 collapsible && open && "[[data-panel-animations=true]_&]:starting:w-0!",
201 collapsible && !open && "pointer-events-none",
202 )}
203 style={
204 isInline
205 ? ({
206 [RESIZABLE_WIDTH_PROPERTY]: `${width}px`,
207 width: maximized
208 ? "100%"
209 : collapsible && !open
210 ? "0px"
211 : `var(${RESIZABLE_WIDTH_PROPERTY})`,
212 transitionDuration: suppressWidthTransition ? "0ms" : undefined,
213 } as CSSProperties)
214 : undefined
215 }
216 data-preview-panel-mode={props.mode}
217 data-preview-panel-maximized={maximized ? "true" : "false"}
218 >
219 {isInline && !maximized ? <RightPanelResizeHandle handlers={handlers} /> : null}
220 {/* Content stays pinned to the right edge, so closing uncovers the chat
221 instead of sliding the tab bar under the title bar controls. The width
222 is passed through explicitly because the property does not inherit. */}
223 <div
224 className={cn(
225 "h-full min-h-0 w-full",
226 collapsible && "overflow-clip",
227 collapsible && !maximized && "flex justify-end [--resizable-width:inherit]",
228 )}
229 >
230 <div
231 className={cn(
232 "flex h-full min-h-0 min-w-0 flex-col",
233 collapsible && !maximized && "shrink-0 [--resizable-width:inherit]",
234 )}
235 style={
236 collapsible && !maximized
237 ? { width: `calc(var(${RESIZABLE_WIDTH_PROPERTY}) - 1px)` }
238 : undefined
239 }
240 >
241 {props.children}
242 </div>
243 </div>
244 </div>
245 );
246}