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

PreviewPanelShell.tsx

216 lines8.2 KB

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