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