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 {
6 type PointerEvent as ReactPointerEvent,
7 type ReactNode,
8 useCallback,
9 useEffect,
10 useLayoutEffect,
11 useRef,
12 useState,
13} from "react";
14
15import { useChatCanvas } from "../chat/ChatCanvasContext";
16import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
17import {
18 findActiveBrowserRecordingRuntimeTabId,
19 useActiveBrowserRecordingTabIds,
20} from "~/browser/browserRecording";
21import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
22import type { BrowserViewportResizeDirection } from "~/browser/browserViewportLayout";
23import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
24import { useRendersServerTabNatively } from "~/browser/previewRuntime";
25import { type ServerBrowserHandle, ServerBrowserSurface } from "~/browser/ServerBrowserSurface";
26import {
27 closeServerPictureInPicture,
28 openServerPictureInPicture,
29 serverPictureInPictureKey,
30 supportsServerPictureInPicture,
31 useServerPictureInPictureKey,
32} from "~/browser/serverPictureInPicture";
33import { Button } from "~/components/ui/button";
34import { toastManager } from "~/components/ui/toast";
35import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
36import { cn } from "~/lib/utils";
37import { useThreadPreviewState } from "~/previewStateStore";
38import {
39 type PreviewMiniPlayerSize,
40 type PreviewMiniPlayerSource,
41 type PreviewMiniPlayerState,
42 previewMiniPlayerSourceKey,
43 usePreviewMiniPlayerStore,
44} from "~/previewMiniPlayerStore";
45import { useRightPanelStore } from "~/rightPanelStore";
46import { useDeviceState } from "~/state/device";
47
48import { DeviceStreamView } from "../device/DeviceStreamView";
49import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
50import type { PreviewStreamViewport } from "@t3tools/client-runtime/preview/server-browser-stream";
51import { previewBridge } from "./previewBridge";
52import {
53 clampPreviewMiniPlayerPosition,
54 NO_PREVIEW_MINI_PLAYER_OBSTACLES,
55 PREVIEW_MINI_PLAYER_CORNER_RADIUS,
56 PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX,
57 type PreviewMiniPlayerFrame,
58 resizePreviewMiniPlayer,
59 resolveDeviceMiniPlayerCornerRadius,
60 resolveDeviceMiniPlayerSourceSize,
61 resolvePreviewMiniPlayerSourceSize,
62} from "./previewMiniPlayerLayout";
63
64interface PointerGesture {
65 readonly pointerId: number;
66 readonly pointerType: string;
67 readonly pointerX: number;
68 readonly pointerY: number;
69 readonly frame: PreviewMiniPlayerFrame;
70 readonly direction: BrowserViewportResizeDirection | null;
71 moved: boolean;
72}
73
74// A touch that travels less than this is a tap on the handle, not a drag.
75const HANDLE_TAP_SLOP_PX = 6;
76
77interface Props {
78 readonly threadRef: ScopedThreadRef;
79 readonly miniPlayer: PreviewMiniPlayerState;
80}
81
82const frameCornerRadius = () => PREVIEW_MINI_PLAYER_CORNER_RADIUS;
83
84// Invisible grab zones straddling each edge; the cursor is the only affordance.
85const RESIZE_HANDLES: ReadonlyArray<{
86 readonly direction: BrowserViewportResizeDirection;
87 readonly className: string;
88}> = [
89 { direction: "north", className: "inset-x-0 -top-1 h-2 cursor-ns-resize" },
90 { direction: "south", className: "inset-x-0 -bottom-1 h-2 cursor-ns-resize" },
91 { direction: "west", className: "inset-y-0 -left-1 w-2 cursor-ew-resize" },
92 { direction: "east", className: "inset-y-0 -right-1 w-2 cursor-ew-resize" },
93 { direction: "northwest", className: "-left-2 -top-2 size-4 cursor-nwse-resize" },
94 { direction: "northeast", className: "-right-2 -top-2 size-4 cursor-nesw-resize" },
95 { direction: "southwest", className: "-bottom-2 -left-2 size-4 cursor-nesw-resize" },
96 { direction: "southeast", className: "-bottom-2 -right-2 size-4 cursor-nwse-resize" },
97];
98
99/** Floats the thread's browser tab or device stream over chat. */
100export function ThreadPreviewMiniPlayer({ threadRef, miniPlayer }: Props) {
101 const { source } = miniPlayer;
102 return source.kind === "browser" ? (
103 <BrowserMiniPlayer
104 key={source.tabId}
105 threadRef={threadRef}
106 tabId={source.tabId}
107 miniPlayer={miniPlayer}
108 />
109 ) : (
110 <DeviceMiniPlayer
111 key={previewMiniPlayerSourceKey(source)}
112 threadRef={threadRef}
113 source={source}
114 miniPlayer={miniPlayer}
115 />
116 );
117}
118
119function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly tabId: string }) {
120 const previewState = useThreadPreviewState(threadRef);
121 const snapshot = previewState.sessions[tabId] ?? null;
122 const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
123 const recordingTabIds = useActiveBrowserRecordingTabIds();
124 const recording =
125 recordingTabIds.has(runtimeTabId) ||
126 findActiveBrowserRecordingRuntimeTabId(threadRef, tabId) !== null;
127 const desktopOverlay = previewState.desktopByTabId[tabId] ?? null;
128 const fittedSourceContent = useBrowserSurfaceStore(
129 (state) => state.byTabId[runtimeTabId]?.fittedSourceContent ?? null,
130 );
131 const nativeServerTab = useRendersServerTabNatively(threadRef.environmentId, snapshot);
132 const serverTab = snapshot?.runtime === "server" && !nativeServerTab;
133 const [streamViewport, setStreamViewport] = useState<PreviewStreamViewport | null>(null);
134 const serverSurfaceRef = useRef<ServerBrowserHandle | null>(null);
135 const serverPictureInPicture =
136 useServerPictureInPictureKey() === serverPictureInPictureKey(threadRef.threadId, tabId);
137 const sourceSize =
138 serverTab && streamViewport
139 ? streamViewport
140 : resolvePreviewMiniPlayerSourceSize(
141 snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT,
142 fittedSourceContent,
143 desktopOverlay?.zoomFactor ?? 1,
144 );
145
146 const openInPanel = () => {
147 usePreviewMiniPlayerStore.getState().close(threadRef);
148 useRightPanelStore.getState().openBrowser(threadRef, tabId);
149 };
150
151 const toggleNativePictureInPicture = async () => {
152 try {
153 if (serverTab) {
154 if (serverPictureInPicture) closeServerPictureInPicture();
155 else
156 await openServerPictureInPicture({
157 ...threadRef,
158 tabId,
159 seed: serverSurfaceRef.current?.canvas() ?? null,
160 });
161 } else if (previewBridge) {
162 const operation = desktopOverlay?.pictureInPicture
163 ? previewBridge.pictureInPicture.close
164 : previewBridge.pictureInPicture.open;
165 await operation(runtimeTabId);
166 }
167 } catch (error) {
168 toastManager.add({
169 type: "error",
170 title: serverTab ? "Unable to pop out preview" : "Unable to update popped-out preview",
171 description: error instanceof Error ? error.message : "An error occurred.",
172 });
173 }
174 };
175
176 if (!snapshot) return null;
177 const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture);
178 const canPopOut = serverTab ? supportsServerPictureInPicture() : true;
179
180 return (
181 <MiniPlayerShell
182 threadRef={threadRef}
183 miniPlayer={miniPlayer}
184 sourceSize={sourceSize}
185 label="Floating browser preview"
186 recording={recording}
187 onOpenInPanel={openInPanel}
188 pillActions={
189 canPopOut ? (
190 <Tooltip>
191 <TooltipTrigger
192 render={
193 <Button
194 variant={poppedOut ? "secondary" : "ghost"}
195 size="icon-xs"
196 aria-label={
197 poppedOut ? "Close popped-out preview" : "Pop preview into separate window"
198 }
199 disabled={!serverTab && !desktopOverlay?.hasWebContents}
200 onPointerDown={(event) => event.stopPropagation()}
201 onClick={toggleNativePictureInPicture}
202 />
203 }
204 >
205 <PictureInPicture2 />
206 </TooltipTrigger>
207 <TooltipPopup side="top">
208 {poppedOut ? "Close separate window" : "Pop into separate window"}
209 </TooltipPopup>
210 </Tooltip>
211 ) : null
212 }
213 >
214 {(frame) =>
215 serverTab ? (
216 <div
217 className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit]"
218 style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}
219 >
220 <ServerBrowserSurface
221 ref={serverSurfaceRef}
222 environmentId={threadRef.environmentId}
223 threadId={threadRef.threadId}
224 tabId={tabId}
225 visible
226 followSize={false}
227 controlPosition="bottom"
228 onViewport={setStreamViewport}
229 className="size-full"
230 />
231 </div>
232 ) : (
233 <>
234 <BrowserSurfaceSlot
235 tabId={runtimeTabId}
236 visible={Boolean(desktopOverlay?.hasWebContents)}
237 cornerRadius={PREVIEW_MINI_PLAYER_CORNER_RADIUS}
238 zIndex={PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX}
239 fitSourceContent
240 layoutVersion={`${frame.x}:${frame.y}`}
241 className="absolute inset-0"
242 />
243 {!desktopOverlay?.hasWebContents ? (
244 <div className="pointer-events-none absolute inset-0 z-[49] flex items-center justify-center rounded-[inherit] bg-muted text-xs text-muted-foreground">
245 Reconnecting preview…
246 </div>
247 ) : null}
248 </>
249 )
250 }
251 </MiniPlayerShell>
252 );
253}
254
255function DeviceMiniPlayer({
256 threadRef,
257 source,
258 miniPlayer,
259}: Props & { readonly source: Extract<PreviewMiniPlayerSource, { kind: "device" }> }) {
260 const { state: deviceState } = useDeviceState(threadRef.environmentId);
261 const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
262 const sourceSize = resolveDeviceMiniPlayerSourceSize(source.platform, screen);
263 const device = deviceState.devices.find(
264 (entry) => entry.hostId === source.hostId && entry.id === source.deviceId,
265 );
266 const hostLabel =
267 deviceState.hosts.find((host) => host.id === source.hostId)?.label ?? "Device host";
268 const cornerRadius = useCallback(
269 (player: PreviewMiniPlayerSize) => resolveDeviceMiniPlayerCornerRadius(source.platform, player),
270 [source.platform],
271 );
272
273 const openInPanel = () => {
274 usePreviewMiniPlayerStore.getState().close(threadRef);
275 useRightPanelStore.getState().openDevice(threadRef, {
276 hostId: source.hostId,
277 deviceId: source.deviceId,
278 platform: source.platform,
279 name: source.name,
280 });
281 };
282
283 return (
284 <MiniPlayerShell
285 threadRef={threadRef}
286 miniPlayer={miniPlayer}
287 sourceSize={sourceSize}
288 label="Floating device preview"
289 onOpenInPanel={openInPanel}
290 cornerRadius={cornerRadius}
291 >
292 {() => (
293 // The stream is DOM, so it takes the band the browser's native webview would.
294 <div
295 className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit]"
296 style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}
297 >
298 <DeviceStreamView
299 environmentId={threadRef.environmentId}
300 platform={source.platform}
301 deviceId={source.deviceId}
302 hostId={source.hostId}
303 deviceName={device?.name ?? source.name}
304 deviceDescription={`${hostLabel} · ${device?.version ?? source.platform}`}
305 visible
306 onScreen={setScreen}
307 />
308 </div>
309 )}
310 </MiniPlayerShell>
311 );
312}
313
314/**
315 * The frame, drag/resize gestures, and hover pill shared by every floating
316 * source. Native clipping and the DOM frame use the same radius so their
317 * separately composited edges stay aligned.
318 */
319function MiniPlayerShell({
320 threadRef,
321 miniPlayer,
322 sourceSize,
323 label,
324 onOpenInPanel,
325 pillActions,
326 recording = false,
327 cornerRadius = frameCornerRadius,
328 children,
329}: {
330 readonly threadRef: ScopedThreadRef;
331 readonly miniPlayer: PreviewMiniPlayerState;
332 readonly sourceSize: PreviewMiniPlayerSize;
333 readonly label: string;
334 readonly onOpenInPanel: () => void;
335 readonly pillActions?: ReactNode;
336 readonly recording?: boolean;
337 /** The clip radius for a given frame; the pill stays inside the curve. */
338 readonly cornerRadius?: (frame: PreviewMiniPlayerSize) => number;
339 readonly children: (frame: PreviewMiniPlayerFrame) => ReactNode;
340}) {
341 const canvas = useChatCanvas();
342 const gestureRef = useRef<PointerGesture | null>(null);
343 // Touch has no hover, so tapping the handle toggles the pill instead. The
344 // toggle waits for the tap's click, which would otherwise land on the pill.
345 const [pillOpen, setPillOpen] = useState(false);
346 const handleTappedRef = useRef(false);
347 const handleRef = useRef<HTMLDivElement | null>(null);
348 // The pill covers the handle, so a tap anywhere else dismisses it.
349 useEffect(() => {
350 if (!pillOpen) return;
351 const dismiss = (event: PointerEvent) => {
352 if (event.target instanceof Node && handleRef.current?.contains(event.target)) return;
353 setPillOpen(false);
354 };
355 document.addEventListener("pointerdown", dismiss, true);
356 return () => document.removeEventListener("pointerdown", dismiss, true);
357 }, [pillOpen]);
358 const container = canvas?.container ?? null;
359 const obstacles = NO_PREVIEW_MINI_PLAYER_OBSTACLES;
360 const sourceKey = previewMiniPlayerSourceKey(miniPlayer.source);
361 const frame = canvas?.previewKey === sourceKey ? canvas.layout.frame : null;
362 const { width: sourceWidth, height: sourceHeight } = sourceSize;
363 const reportPreview = canvas?.reportPreview;
364 const clearPreview = canvas?.clearPreview;
365 useLayoutEffect(() => {
366 reportPreview?.({
367 key: sourceKey,
368 width: miniPlayer.width,
369 position: miniPlayer.position,
370 lastInteraction: miniPlayer.lastInteraction,
371 source: { width: sourceWidth, height: sourceHeight },
372 });
373 }, [
374 reportPreview,
375 sourceKey,
376 miniPlayer.width,
377 miniPlayer.position,
378 miniPlayer.lastInteraction,
379 sourceWidth,
380 sourceHeight,
381 ]);
382 useLayoutEffect(() => () => clearPreview?.(sourceKey), [clearPreview, sourceKey]);
383
384 const radius = frame ? cornerRadius(frame) : PREVIEW_MINI_PLAYER_CORNER_RADIUS;
385 // Inside a wide curve the default 8px inset would land on the clipped-away corner.
386 const pillInset = Math.max(8, Math.round(radius * 0.55));
387
388 const close = () => {
389 usePreviewMiniPlayerStore.getState().close(threadRef);
390 };
391
392 const beginGesture = (
393 event: ReactPointerEvent<HTMLElement>,
394 direction: BrowserViewportResizeDirection | null,
395 ) => {
396 if (event.button !== 0 || !frame) return;
397 gestureRef.current = {
398 pointerId: event.pointerId,
399 pointerType: event.pointerType,
400 pointerX: event.clientX,
401 pointerY: event.clientY,
402 frame,
403 direction,
404 moved: false,
405 };
406 event.currentTarget.setPointerCapture(event.pointerId);
407 event.preventDefault();
408 event.stopPropagation();
409 };
410
411 const handlePointerMove = (event: ReactPointerEvent<HTMLElement>) => {
412 const gesture = gestureRef.current;
413 if (!gesture || gesture.pointerId !== event.pointerId || !container) return;
414 const delta = { x: event.clientX - gesture.pointerX, y: event.clientY - gesture.pointerY };
415 if (!gesture.moved && Math.hypot(delta.x, delta.y) < HANDLE_TAP_SLOP_PX) return;
416 gesture.moved = true;
417 const store = usePreviewMiniPlayerStore.getState();
418 if (gesture.direction === null) {
419 store.move(
420 threadRef,
421 sourceKey,
422 clampPreviewMiniPlayerPosition(
423 { x: gesture.frame.x + delta.x, y: gesture.frame.y + delta.y },
424 container,
425 gesture.frame,
426 obstacles,
427 ),
428 );
429 return;
430 }
431 const next = resizePreviewMiniPlayer({
432 start: gesture.frame,
433 direction: gesture.direction,
434 delta,
435 source: sourceSize,
436 container,
437 obstacles,
438 });
439 store.resize(threadRef, sourceKey, next.width, { x: next.x, y: next.y });
440 };
441
442 const endGesture = (event: ReactPointerEvent<HTMLElement>) => {
443 const gesture = gestureRef.current;
444 if (gesture?.pointerId !== event.pointerId) return;
445 gestureRef.current = null;
446 handleTappedRef.current =
447 event.type === "pointerup" &&
448 gesture.direction === null &&
449 gesture.pointerType === "touch" &&
450 !gesture.moved;
451 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
452 event.currentTarget.releasePointerCapture(event.pointerId);
453 }
454 };
455
456 return (
457 <div className="pointer-events-none absolute inset-0">
458 {frame ? (
459 <section
460 aria-label={label}
461 data-preview-mini-player={sourceKey}
462 className="pointer-events-none absolute select-none"
463 style={{
464 left: frame.x,
465 top: frame.y,
466 width: frame.width,
467 height: frame.height,
468 borderRadius: radius,
469 }}
470 >
471 <div
472 ref={handleRef}
473 data-pill-open={pillOpen ? "" : undefined}
474 className="group pointer-events-auto absolute z-[49] size-3 touch-none cursor-grab active:cursor-grabbing pointer-coarse:-m-2.5 pointer-coarse:size-8"
475 style={{ right: pillInset, top: pillInset }}
476 onPointerDown={(event) => beginGesture(event, null)}
477 onPointerMove={handlePointerMove}
478 onPointerUp={endGesture}
479 onPointerCancel={endGesture}
480 onClick={() => {
481 if (!handleTappedRef.current) return;
482 handleTappedRef.current = false;
483 setPillOpen((open) => !open);
484 }}
485 >
486 <div
487 role={recording ? "status" : undefined}
488 aria-label={recording ? "Recording preview" : undefined}
489 aria-hidden={!recording}
490 className="absolute right-0 top-0 size-2 transition-opacity group-hover:opacity-0 group-focus-within:opacity-0 group-data-pill-open:opacity-0 pointer-coarse:right-2.5 pointer-coarse:top-2.5"
491 >
492 <span
493 className={cn(
494 "block size-2 rounded-full shadow-sm ring-1 ring-background/70",
495 recording
496 ? "bg-destructive motion-safe:animate-status-pulse"
497 : "bg-foreground/25",
498 )}
499 />
500 </div>
501 <div 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 group-data-pill-open:pointer-events-auto group-data-pill-open:opacity-100 active:cursor-grabbing pointer-coarse:right-2.5 pointer-coarse:top-2.5">
502 {recording ? (
503 <span aria-hidden className="flex size-6 shrink-0 items-center justify-center">
504 <span className="size-2 rounded-full bg-destructive motion-safe:animate-status-pulse" />
505 </span>
506 ) : null}
507 <Tooltip>
508 <TooltipTrigger
509 render={
510 <Button
511 variant="ghost"
512 size="icon-xs"
513 aria-label="Open preview in right panel"
514 onPointerDown={(event) => event.stopPropagation()}
515 onClick={onOpenInPanel}
516 />
517 }
518 >
519 <PanelRightIcon />
520 </TooltipTrigger>
521 <TooltipPopup side="top">Open in right panel</TooltipPopup>
522 </Tooltip>
523 {pillActions}
524 <Tooltip>
525 <TooltipTrigger
526 render={
527 <Button
528 variant="ghost"
529 size="icon-xs"
530 aria-label="Close floating preview"
531 onPointerDown={(event) => event.stopPropagation()}
532 onClick={close}
533 />
534 }
535 >
536 <XIcon />
537 </TooltipTrigger>
538 <TooltipPopup side="top">Close floating preview</TooltipPopup>
539 </Tooltip>
540 </div>
541 </div>
542
543 <div className="absolute inset-0 z-[47] rounded-[inherit] bg-muted shadow-2xl/35" />
544 {children(frame)}
545 <div className="pointer-events-none absolute inset-0 z-[49] rounded-[inherit] ring-1 ring-inset ring-border/80" />
546 {RESIZE_HANDLES.map(({ direction, className }) => (
547 <div
548 key={direction}
549 role="presentation"
550 data-preview-mini-player-resize={direction}
551 className={cn("pointer-events-auto absolute z-[49] touch-none", className)}
552 onPointerDown={(event) => beginGesture(event, direction)}
553 onPointerMove={handlePointerMove}
554 onPointerUp={endGesture}
555 onPointerCancel={endGesture}
556 />
557 ))}
558 </section>
559 ) : null}
560 </div>
561 );
562}