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

PreviewPanelShell.tsx

239 lines9.2 KB

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