Open History to see the last commit
1"use client";
2
3import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts";
4import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
5import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef, useState } from "react";
6
7import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
8import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
9import type { BrowserViewportResizeDirection } from "~/browser/browserViewportLayout";
10import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
11import { Button } from "~/components/ui/button";
12import { toastManager } from "~/components/ui/toast";
13import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
14import { cn } from "~/lib/utils";
15import { useThreadPreviewState } from "~/previewStateStore";
16import {
17 type PreviewMiniPlayerSize,
18 selectThreadPreviewMiniPlayer,
19 usePreviewMiniPlayerStore,
20} from "~/previewMiniPlayerStore";
21import { useRightPanelStore } from "~/rightPanelStore";
22
23import { previewBridge } from "./previewBridge";
24import {
25 clampPreviewMiniPlayerPosition,
26 PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX,
27 type PreviewMiniPlayerFrame,
28 resizePreviewMiniPlayer,
29 resolvePreviewMiniPlayerFrame,
30 resolvePreviewMiniPlayerSourceSize,
31} from "./previewMiniPlayerLayout";
32
33interface PointerGesture {
34 readonly pointerId: number;
35 readonly pointerX: number;
36 readonly pointerY: number;
37 readonly frame: PreviewMiniPlayerFrame;
38 readonly direction: BrowserViewportResizeDirection | null;
39}
40
41interface Props {
42 readonly threadRef: ScopedThreadRef;
43 readonly tabId: string;
44 readonly bottomInset: number;
45}
46
47const PREVIEW_MINI_PLAYER_CORNER_RADIUS = 12;
48
49// Invisible grab zones straddling each edge; the cursor is the only affordance.
50const RESIZE_HANDLES: ReadonlyArray<{
51 readonly direction: BrowserViewportResizeDirection;
52 readonly className: string;
53}> = [
54 { direction: "north", className: "inset-x-0 -top-1 h-2 cursor-ns-resize" },
55 { direction: "south", className: "inset-x-0 -bottom-1 h-2 cursor-ns-resize" },
56 { direction: "west", className: "inset-y-0 -left-1 w-2 cursor-ew-resize" },
57 { direction: "east", className: "inset-y-0 -right-1 w-2 cursor-ew-resize" },
58 { direction: "northwest", className: "-left-2 -top-2 size-4 cursor-nwse-resize" },
59 { direction: "northeast", className: "-right-2 -top-2 size-4 cursor-nesw-resize" },
60 { direction: "southwest", className: "-bottom-2 -left-2 size-4 cursor-nesw-resize" },
61 { direction: "southeast", className: "-bottom-2 -right-2 size-4 cursor-nwse-resize" },
62];
63
64/**
65 * Floats the thread's browser surface over chat. Native clipping and the DOM
66 * frame use the same radius so their separately composited edges stay aligned.
67 */
68export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props) {
69 const containerRef = useRef<HTMLDivElement | null>(null);
70 const gestureRef = useRef<PointerGesture | null>(null);
71 const [container, setContainer] = useState<PreviewMiniPlayerSize | null>(null);
72 const miniPlayer = usePreviewMiniPlayerStore((state) =>
73 selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),
74 );
75 const previewState = useThreadPreviewState(threadRef);
76 const snapshot = previewState.sessions[tabId] ?? null;
77 const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
78 const desktopOverlay = previewState.desktopByTabId[tabId] ?? null;
79 const fittedSourceContent = useBrowserSurfaceStore(
80 (state) => state.byTabId[runtimeTabId]?.fittedSourceContent ?? null,
81 );
82 const source = resolvePreviewMiniPlayerSourceSize(
83 snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT,
84 fittedSourceContent,
85 desktopOverlay?.zoomFactor ?? 1,
86 );
87 const frame =
88 container && miniPlayer?.tabId === tabId
89 ? resolvePreviewMiniPlayerFrame({
90 width: miniPlayer.width,
91 position: miniPlayer.position,
92 source,
93 container,
94 bottomInset,
95 })
96 : null;
97
98 const close = () => {
99 usePreviewMiniPlayerStore.getState().close(threadRef);
100 };
101
102 const openInPanel = () => {
103 usePreviewMiniPlayerStore.getState().close(threadRef);
104 useRightPanelStore.getState().openBrowser(threadRef, tabId);
105 };
106
107 const toggleNativePictureInPicture = () => {
108 if (!previewBridge) return;
109 const operation = desktopOverlay?.pictureInPicture
110 ? previewBridge.pictureInPicture.close
111 : previewBridge.pictureInPicture.open;
112 void operation(runtimeTabId).catch((error) => {
113 toastManager.add({
114 type: "error",
115 title: "Unable to update popped-out preview",
116 description: error instanceof Error ? error.message : "An error occurred.",
117 });
118 });
119 };
120
121 useLayoutEffect(() => {
122 const element = containerRef.current;
123 if (!element) return;
124 const measure = () => {
125 setContainer((current) =>
126 current?.width === element.clientWidth && current.height === element.clientHeight
127 ? current
128 : { width: element.clientWidth, height: element.clientHeight },
129 );
130 };
131 measure();
132 if (typeof ResizeObserver === "undefined") return;
133 const observer = new ResizeObserver(measure);
134 observer.observe(element);
135 return () => observer.disconnect();
136 }, []);
137
138 const beginGesture = (
139 event: ReactPointerEvent<HTMLElement>,
140 direction: BrowserViewportResizeDirection | null,
141 ) => {
142 if (event.button !== 0 || !frame) return;
143 gestureRef.current = {
144 pointerId: event.pointerId,
145 pointerX: event.clientX,
146 pointerY: event.clientY,
147 frame,
148 direction,
149 };
150 event.currentTarget.setPointerCapture(event.pointerId);
151 event.preventDefault();
152 event.stopPropagation();
153 };
154
155 const handlePointerMove = (event: ReactPointerEvent<HTMLElement>) => {
156 const gesture = gestureRef.current;
157 if (!gesture || gesture.pointerId !== event.pointerId || !container) return;
158 const delta = { x: event.clientX - gesture.pointerX, y: event.clientY - gesture.pointerY };
159 const store = usePreviewMiniPlayerStore.getState();
160 if (gesture.direction === null) {
161 store.move(
162 threadRef,
163 tabId,
164 clampPreviewMiniPlayerPosition(
165 { x: gesture.frame.x + delta.x, y: gesture.frame.y + delta.y },
166 container,
167 gesture.frame,
168 bottomInset,
169 ),
170 );
171 return;
172 }
173 const next = resizePreviewMiniPlayer({
174 start: gesture.frame,
175 direction: gesture.direction,
176 delta,
177 source,
178 container,
179 bottomInset,
180 });
181 store.resize(threadRef, tabId, next.width);
182 store.move(threadRef, tabId, { x: next.x, y: next.y });
183 };
184
185 const endGesture = (event: ReactPointerEvent<HTMLElement>) => {
186 if (gestureRef.current?.pointerId !== event.pointerId) return;
187 gestureRef.current = null;
188 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
189 event.currentTarget.releasePointerCapture(event.pointerId);
190 }
191 };
192
193 if (!snapshot || miniPlayer?.tabId !== tabId) return null;
194
195 return (
196 <div ref={containerRef} className="pointer-events-none absolute inset-0">
197 {frame ? (
198 <section
199 aria-label="Floating browser preview"
200 data-preview-mini-player={tabId}
201 className="pointer-events-none absolute select-none"
202 style={{
203 left: frame.x,
204 top: frame.y,
205 width: frame.width,
206 height: frame.height,
207 borderRadius: PREVIEW_MINI_PLAYER_CORNER_RADIUS,
208 }}
209 >
210 <div className="group pointer-events-auto absolute right-2 top-2 z-[49] size-3">
211 <div
212 aria-hidden="true"
213 className="absolute right-0 top-0 size-2 rounded-full bg-foreground/25 shadow-sm ring-1 ring-background/70 transition-opacity group-hover:opacity-0 group-focus-within:opacity-0"
214 />
215 <div
216 className="pointer-events-none absolute right-0 top-0 flex h-8 cursor-grab items-center gap-0.5 rounded-lg border border-border/80 bg-popover/92 p-0.5 opacity-0 shadow-lg/20 backdrop-blur-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 active:cursor-grabbing"
217 onPointerDown={(event) => beginGesture(event, null)}
218 onPointerMove={handlePointerMove}
219 onPointerUp={endGesture}
220 onPointerCancel={endGesture}
221 >
222 <Tooltip>
223 <TooltipTrigger
224 render={
225 <Button
226 variant="ghost"
227 size="icon-xs"
228 aria-label="Open preview in right panel"
229 onPointerDown={(event) => event.stopPropagation()}
230 onClick={openInPanel}
231 />
232 }
233 >
234 <PanelRightIcon />
235 </TooltipTrigger>
236 <TooltipPopup side="top">Open in right panel</TooltipPopup>
237 </Tooltip>
238 <Tooltip>
239 <TooltipTrigger
240 render={
241 <Button
242 variant={desktopOverlay?.pictureInPicture ? "secondary" : "ghost"}
243 size="icon-xs"
244 aria-label={
245 desktopOverlay?.pictureInPicture
246 ? "Close popped-out preview"
247 : "Pop preview into separate window"
248 }
249 disabled={!desktopOverlay?.hasWebContents}
250 onPointerDown={(event) => event.stopPropagation()}
251 onClick={toggleNativePictureInPicture}
252 />
253 }
254 >
255 <PictureInPicture2 />
256 </TooltipTrigger>
257 <TooltipPopup side="top">
258 {desktopOverlay?.pictureInPicture
259 ? "Close separate window"
260 : "Pop into separate window"}
261 </TooltipPopup>
262 </Tooltip>
263 <Tooltip>
264 <TooltipTrigger
265 render={
266 <Button
267 variant="ghost"
268 size="icon-xs"
269 aria-label="Close floating preview"
270 onPointerDown={(event) => event.stopPropagation()}
271 onClick={close}
272 />
273 }
274 >
275 <XIcon />
276 </TooltipTrigger>
277 <TooltipPopup side="top">Close floating preview</TooltipPopup>
278 </Tooltip>
279 </div>
280 </div>
281
282 <div className="absolute inset-0 z-[47] rounded-[inherit] bg-muted shadow-2xl/35" />
283 <BrowserSurfaceSlot
284 tabId={runtimeTabId}
285 visible={Boolean(desktopOverlay?.hasWebContents)}
286 cornerRadius={PREVIEW_MINI_PLAYER_CORNER_RADIUS}
287 zIndex={PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX}
288 fitSourceContent
289 layoutVersion={`${frame.x}:${frame.y}`}
290 className="absolute inset-0"
291 />
292 <div className="pointer-events-none absolute inset-0 z-[49] rounded-[inherit] ring-1 ring-inset ring-border/80" />
293 {!desktopOverlay?.hasWebContents ? (
294 <div className="pointer-events-none absolute inset-0 z-[49] flex items-center justify-center rounded-[inherit] bg-muted text-xs text-muted-foreground">
295 Reconnecting preview…
296 </div>
297 ) : null}
298 {RESIZE_HANDLES.map(({ direction, className }) => (
299 <div
300 key={direction}
301 role="presentation"
302 data-preview-mini-player-resize={direction}
303 className={cn("pointer-events-auto absolute z-[49] touch-none", className)}
304 onPointerDown={(event) => beginGesture(event, direction)}
305 onPointerMove={handlePointerMove}
306 onPointerUp={endGesture}
307 onPointerCancel={endGesture}
308 />
309 ))}
310 </section>
311 ) : null}
312 </div>
313 );
314}