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

ThreadPreviewMiniPlayer.tsx

832 lines32.0 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m } from "~/i18n/messages";
3import {
4 type CuaWindowPreviewFrame,
5 FILL_PREVIEW_VIEWPORT,
6 type ScopedThreadRef,
7} from "@t3tools/contracts";
8import { previewPdfAssetUrl } from "@t3tools/shared/preview";
9import { useEnvironmentHttpBaseUrl } from "~/state/environments";
10import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
11import {
12 type PointerEvent as ReactPointerEvent,
13 type ReactNode,
14 useEffect,
15 useEffectEvent,
16 useLayoutEffect,
17 useRef,
18 useState,
19} from "react";
20import { T, useGT } from "gt-react";
21import { create } from "zustand";
22import { useAtomValue } from "@effect/atom-react";
23import { scopedThreadKey } from "@t3tools/client-runtime/environment";
24​
25import { useChatCanvas } from "../chat/ChatCanvasContext";
26import type { ChatCanvasPreview } from "../chat/chatCanvasLayout";
27import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
28import {
29 findActiveBrowserRecordingRuntimeTabId,
30 useActiveBrowserRecordingTabIds,
31} from "~/browser/browserRecording";
32import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
33import type { BrowserViewportResizeDirection } from "~/browser/browserViewportLayout";
34import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
35import { rendersServerTabNatively } from "~/browser/previewRuntime";
36import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
37import { type ServerBrowserHandle, ServerBrowserSurface } from "~/browser/ServerBrowserSurface";
38import {
39 closeServerPictureInPicture,
40 openServerPictureInPicture,
41 serverPictureInPictureKey,
42 supportsServerPictureInPicture,
43 useServerPictureInPictureKey,
44} from "~/browser/serverPictureInPicture";
45import { useBrowserLayoutZoomFactor } from "~/browser/useBrowserLayoutZoomFactor";
46import { Button } from "~/components/ui/button";
47import { toastManager } from "~/components/ui/toast";
48import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
49import { cn } from "~/lib/utils";
50import { useThreadPreviewState } from "~/previewStateStore";
51import {
52 type PreviewMiniPlayerSize,
53 type PreviewMiniPlayerSource,
54 type PreviewMiniPlayerState,
55 browserMiniPlayerSource,
56 previewMiniPlayerSourceKey,
57 usePreviewMiniPlayerStore,
58} from "~/previewMiniPlayerStore";
59import { useRightPanelStore } from "~/rightPanelStore";
60import { useCuaWindowPreview } from "~/state/cua";
61import { useDeviceState } from "~/state/device";
62import { useAssetUrlState } from "~/assets/assetUrls";
63​
64import { DeviceStreamView } from "../device/DeviceStreamView";
65import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
66import { Atom } from "effect/reactivity";
67import { deviceScreenKey, deviceStreamScreenAtom } from "../device/deviceStreamSession";
68import type { PreviewStreamViewport } from "@t3tools/client-runtime/preview/server-browser-stream";
69import type { ComputerUsePreview } from "./computerUsePreview";
70import { previewBridge } from "./previewBridge";
71import { PreviewUnreachable } from "./PreviewUnreachable";
72import { showPreviewPopup } from "./showPreviewPopup";
73import {
74 type PreviewMiniPlayerGesture,
75 settlePreviewMiniPlayerResize,
76 stepPreviewMiniPlayerGesture,
77} from "./previewMiniPlayerGesture";
78import {
79 PREVIEW_MINI_PLAYER_CORNER_RADIUS,
80 PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX,
81 type PreviewMiniPlayerFrame,
82 resolveDeviceMiniPlayerCornerRadius,
83 resolveDeviceMiniPlayerSourceSize,
84 resolvePreviewMiniPlayerSourceSize,
85} from "./previewMiniPlayerLayout";
86​
87interface Props {
88 readonly threadRef: ScopedThreadRef;
89 readonly miniPlayer: PreviewMiniPlayerState;
91​
92const frameCornerRadius = () => PREVIEW_MINI_PLAYER_CORNER_RADIUS;
93​
94const RESIZE_HANDLES: ReadonlyArray<{
95 readonly direction: BrowserViewportResizeDirection;
96 readonly className: string;
97}> = [
98 { direction: "north", className: "inset-x-0 -top-1 h-2 cursor-ns-resize" },
99 { direction: "south", className: "inset-x-0 -bottom-1 h-2 cursor-ns-resize" },
100 { direction: "west", className: "inset-y-0 -left-1 w-2 cursor-ew-resize" },
101 { direction: "east", className: "inset-y-0 -right-1 w-2 cursor-ew-resize" },
102 { direction: "northwest", className: "-left-2 -top-2 size-4 cursor-nwse-resize" },
103 { direction: "northeast", className: "-right-2 -top-2 size-4 cursor-nesw-resize" },
104 { direction: "southwest", className: "-bottom-2 -left-2 size-4 cursor-nesw-resize" },
105 { direction: "southeast", className: "-bottom-2 -right-2 size-4 cursor-nwse-resize" },
106];
107​
108// What the stream reports about its source. It lives outside the player so the
109// chat canvas lays out the frame from the same source size the player uses. One
110// slot is enough, since only the shown thread renders a player, and it keeps the
111// store from collecting an entry for every tab a session ever streamed.
112const useStreamedSourceSize = create<{
113 readonly key: string;
114 readonly viewport: PreviewStreamViewport;
115} | null>(() => null);
116​
117// The source size a resize in progress lays the frame out from, so a source that changes shape
118// under a held handle cannot resize the player by itself. Same single slot as above.
119const useHeldSourceSize = create<{
120 readonly key: string;
121 readonly source: PreviewMiniPlayerSize;
122} | null>(() => null);
123// Before the first frame arrives, the computer card assumes a laptop-sized window.
124const COMPUTER_DEFAULT_SOURCE_SIZE = { width: 1280, height: 800 } as const;
125​
126const NO_DEVICE_SCREEN_ATOM = Atom.make<DeviceScreenSize | null>(null).pipe(
127 Atom.withLabel("device-stream-screen:none"),
128);
129​
130const streamedSourceKey = (threadRef: ScopedThreadRef, sourceKey: string) =>
131 `${scopedThreadKey(threadRef)}\u0000${sourceKey}`;
132​
133// The mini player's device stream view, named so the canvas can read the
134// screen size that view reports.
135const miniPlayerDeviceViewId = (
136 threadRef: ScopedThreadRef,
137 source: Extract<PreviewMiniPlayerSource, { kind: "device" }>,
138) =>
139 `preview-mini-player\u0000${scopedThreadKey(threadRef)}\u0000${deviceScreenKey(threadRef.environmentId, source.hostId, source.deviceId)}`;
140​
141function useBrowserMiniPlayerSource(threadRef: ScopedThreadRef | null, tabId: string | null) {
142 const previewState = useThreadPreviewState(threadRef);
143 const snapshot = tabId === null ? null : (previewState.sessions[tabId] ?? null);
144 const runtimeTabId =
145 threadRef && tabId !== null
146 ? previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId)
147 : null;
148 const desktopOverlay = tabId === null ? null : (previewState.desktopByTabId[tabId] ?? null);
149 const layoutZoomFactor = useBrowserLayoutZoomFactor(desktopOverlay?.zoomFactor ?? 1);
150 const fittedSourceContent = useBrowserSurfaceStore((state) =>
151 runtimeTabId === null ? null : (state.byTabId[runtimeTabId]?.fittedSourceContent ?? null),
152 );
153 const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
154 const serverTab =
155 threadRef !== null &&
156 snapshot?.runtime === "server" &&
157 !rendersServerTabNatively(threadRef.environmentId, primaryEnvironmentId, snapshot);
158 const streamViewport = useStreamedSourceSize((state) =>
159 threadRef &&
160 tabId !== null &&
161 state?.key ===
162 streamedSourceKey(threadRef, previewMiniPlayerSourceKey(browserMiniPlayerSource(tabId)))
163 ? state.viewport
164 : null,
165 );
166 const sourceSize: PreviewMiniPlayerSize =
167 serverTab && streamViewport
168 ? streamViewport
169 : resolvePreviewMiniPlayerSourceSize(
170 snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT,
171 fittedSourceContent,
172 layoutZoomFactor,
173 );
174 return { serverEpoch: previewState.serverEpoch, snapshot, desktopOverlay, serverTab, sourceSize };
176​
177/** The mini player as the chat canvas lays it out; null when no player renders. */
178export function useThreadPreviewCanvasSource(
179 threadRef: ScopedThreadRef | null,
180 miniPlayer: PreviewMiniPlayerState | null,
181): ChatCanvasPreview | null {
182 const source = miniPlayer?.source ?? null;
183 const browser = useBrowserMiniPlayerSource(
184 threadRef,
185 source?.kind === "browser" ? source.tabId : null,
186 );
187 const sourceKey = source ? previewMiniPlayerSourceKey(source) : null;
188 const screen = useAtomValue(
189 threadRef && source?.kind === "device"
190 ? deviceStreamScreenAtom(miniPlayerDeviceViewId(threadRef, source))
191 : NO_DEVICE_SCREEN_ATOM,
192 );
193 const heldSource = useHeldSourceSize((state) =>
194 threadRef && sourceKey !== null && state?.key === streamedSourceKey(threadRef, sourceKey)
195 ? state.source
196 : null,
197 );
198 const computerSize = useStreamedSourceSize((state) =>
199 threadRef &&
200 source?.kind === "computer" &&
201 state?.key === streamedSourceKey(threadRef, sourceKey!)
202 ? state.viewport
203 : null,
204 );
205 if (!miniPlayer || !source || sourceKey === null) return null;
206 if (source.kind === "browser" && !browser.snapshot) return null;
207 return {
208 key: sourceKey,
209 width: miniPlayer.width,
210 position: miniPlayer.position,
211 lastInteraction: miniPlayer.lastInteraction,
212 source:
213 heldSource ??
214 (source.kind === "browser"
215 ? browser.sourceSize
216 : source.kind === "device"
217 ? resolveDeviceMiniPlayerSourceSize(source.platform, screen)
218 : (computerSize ?? COMPUTER_DEFAULT_SOURCE_SIZE)),
219 };
221​
222export function ThreadPreviewMiniPlayer({
223 threadRef,
224 miniPlayer,
225 computerUse = null,
226}: Props & { readonly computerUse?: ComputerUsePreview | null }) {
227 const { source } = miniPlayer;
228 switch (source.kind) {
229 case "browser":
230 return (
231 <BrowserMiniPlayer
232 key={source.tabId}
233 threadRef={threadRef}
234 tabId={source.tabId}
235 miniPlayer={miniPlayer}
236 />
237 );
238 case "device":
239 return (
240 <DeviceMiniPlayer
241 key={previewMiniPlayerSourceKey(source)}
242 threadRef={threadRef}
243 source={source}
244 miniPlayer={miniPlayer}
245 />
246 );
247 case "computer":
248 return (
249 <ComputerMiniPlayer threadRef={threadRef} miniPlayer={miniPlayer} preview={computerUse} />
250 );
251 }
253​
254/**
255 * The window an agent drives on the host computer. While a computer use turn
256 * runs, the server captures that window every second and a half and streams
257 * it here; the capture runs only while this card is mounted. Between turns the
258 * card keeps the last frame instead of going blank.
259 */
260function ComputerMiniPlayer({
261 threadRef,
262 miniPlayer,
263 preview,
264}: Props & { readonly preview: ComputerUsePreview | null }) {
265 const gt = useGT();
266 const live = useCuaWindowPreview(threadRef);
267 const [lastFrame, setLastFrame] = useState<CuaWindowPreviewFrame | null>(null);
268 const liveFrame = live.status === "live" ? (live.frame ?? null) : null;
269 if (liveFrame !== null && liveFrame !== lastFrame) setLastFrame(liveFrame);
270 const frame = liveFrame ?? lastFrame;
271 const src = frame ? `data:${frame.mimeType};base64,${frame.dataBase64}` : null;
272 const sourceSize =
273 frame && frame.width > 0 && frame.height > 0
274 ? { width: frame.width, height: frame.height }
275 : COMPUTER_DEFAULT_SOURCE_SIZE;
276 const viewportKey = streamedSourceKey(threadRef, previewMiniPlayerSourceKey(miniPlayer.source));
277 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Publishes the frame size to the store the chat canvas lays this card out from.
278 useLayoutEffect(() => {
279 useStreamedSourceSize.setState(
280 (state) =>
281 state?.key === viewportKey &&
282 state.viewport.width === sourceSize.width &&
283 state.viewport.height === sourceSize.height
284 ? state
285 : { key: viewportKey, viewport: { width: sourceSize.width, height: sourceSize.height } },
286 true,
287 );
288 }, [viewportKey, sourceSize.width, sourceSize.height]);
289 const label = frame?.appName ?? preview?.appName ?? gt("Computer");
290 const caption =
291 frame?.windowTitle && frame.windowTitle !== label ? `${label} · ${frame.windowTitle}` : label;
292 const appIcon = useAssetUrlState(
293 threadRef.environmentId,
294 preview?.app ? { _tag: "native-app-icon", app: preview.app } : null,
295 );
296​
297 return (
298 <MiniPlayerShell
299 threadRef={threadRef}
300 miniPlayer={miniPlayer}
301 sourceSize={sourceSize}
302 label={gt("Floating computer use preview")}
303 recording={live.status === "live" || preview?.inProgress === true}
304 >
305 {() => (
306 <div
307 className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit] bg-muted"
308 style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}
309 >
310 {src ? (
311 <img
312 src={src}
313 alt={caption}
314 decoding="async"
315 draggable={false}
316 className="size-full select-none object-contain"
317 />
318 ) : (
319 <div className="flex size-full items-center justify-center text-xs text-muted-foreground">
320 {live.status === "unavailable"
321 ? gt("Preview unavailable")
322 : gt("Waiting for the agent…")}
323 </div>
324 )}
325 {live.status === "unavailable" && live.detail ? (
326 <div className="pointer-events-none absolute inset-x-0 top-0 truncate bg-background/80 px-2.5 py-1 text-2xs text-muted-foreground">
327 {live.detail}
328 </div>
329 ) : null}
330 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-gradient-to-t from-background/85 to-background/0 px-2.5 pt-5 pb-2 text-2xs text-foreground">
331 {appIcon._tag === "Success" ? (
332 <img src={appIcon.url} alt="" aria-hidden className="size-3.5 shrink-0" />
333 ) : null}
334 <span className="truncate">{caption}</span>
335 </div>
336 </div>
337 )}
338 </MiniPlayerShell>
339 );
341​
342function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly tabId: string }) {
343 const gt = useGT();
344 const httpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
345 const { serverEpoch, snapshot, desktopOverlay, serverTab, sourceSize } =
346 useBrowserMiniPlayerSource(threadRef, tabId);
347 const runtimeTabId = previewRuntimeTabId(threadRef, serverEpoch, tabId);
348 const recordingTabIds = useActiveBrowserRecordingTabIds();
349 const recording =
350 recordingTabIds.has(runtimeTabId) ||
351 findActiveBrowserRecordingRuntimeTabId(threadRef, tabId) !== null;
352 const serverSurfaceRef = useRef<ServerBrowserHandle | null>(null);
353 const serverPictureInPicture =
354 useServerPictureInPictureKey() === serverPictureInPictureKey(threadRef.threadId, tabId);
355 const viewportKey = streamedSourceKey(
356 threadRef,
357 previewMiniPlayerSourceKey(browserMiniPlayerSource(tabId)),
358 );
359​
360 const openInPanel = () => {
361 usePreviewMiniPlayerStore.getState().close(threadRef);
362 useRightPanelStore.getState().openBrowser(threadRef, tabId);
363 };
364​
365 const toggleNativePictureInPicture = async () => {
366 try {
367 if (serverTab) {
368 if (serverPictureInPicture) closeServerPictureInPicture();
369 else
370 await openServerPictureInPicture({
371 ...threadRef,
372 tabId,
373 seed: serverSurfaceRef.current?.canvas() ?? null,
374 });
375 } else if (previewBridge) {
376 const operation = desktopOverlay?.pictureInPicture
377 ? previewBridge.pictureInPicture.close
378 : previewBridge.pictureInPicture.open;
379 await operation(runtimeTabId);
380 }
381 } catch (error) {
382 toastManager.add({
383 type: "error",
384 title: serverTab
385 ? gt("Unable to pop out preview")
386 : gt("Unable to update popped-out preview"),
387 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
388 });
389 }
390 };
391​
392 if (!snapshot) return null;
393 const pdfUrl =
394 snapshot.navStatus._tag === "Success"
395 ? previewPdfAssetUrl(snapshot.navStatus.url, httpBaseUrl)
396 : null;
397 const loadFailed = snapshot.navStatus._tag === "LoadFailed" ? snapshot.navStatus : null;
398 const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture);
399 const canPopOut = serverTab
400 ? poppedOut || (pdfUrl === null && supportsServerPictureInPicture())
401 : true;
402​
403 return (
404 <MiniPlayerShell
405 threadRef={threadRef}
406 miniPlayer={miniPlayer}
407 sourceSize={sourceSize}
408 label={gt("Floating browser preview")}
409 recording={recording}
410 onOpenInPanel={openInPanel}
411 pillActions={
412 canPopOut ? (
413 <Tooltip>
414 <TooltipTrigger
415 render={
416 <Button
417 variant={poppedOut ? "secondary" : "ghost"}
418 size="icon-xs"
419 aria-label={
420 poppedOut
421 ? gt("Close popped-out preview")
422 : gt("Pop preview into separate window")
423 }
424 disabled={!serverTab && !desktopOverlay?.hasWebContents}
425 onPointerDown={(event) => event.stopPropagation()}
426 onClick={toggleNativePictureInPicture}
427 />
428 }
429 >
430 <PictureInPicture2 />
431 </TooltipTrigger>
432 <TooltipPopup side="top">
433 {poppedOut ? gt("Close separate window") : gt("Pop into separate window")}
434 </TooltipPopup>
435 </Tooltip>
436 ) : null
437 }
438 >
439 {(frame) =>
440 serverTab ? (
441 <div
442 className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit]"
443 style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}
444 >
445 <ServerBrowserSurface
446 ref={serverSurfaceRef}
447 environmentId={threadRef.environmentId}
448 threadId={threadRef.threadId}
449 tabId={tabId}
450 pdfUrl={pdfUrl}
451 visible
452 followSize={false}
453 controlPosition="bottom"
454 onViewport={(viewport) =>
455 useStreamedSourceSize.setState(
456 (state) =>
457 state?.key === viewportKey &&
458 state.viewport.width === viewport.width &&
459 state.viewport.height === viewport.height
460 ? state
461 : { key: viewportKey, viewport },
462 true,
463 )
464 }
465 onPopup={(popupTabId) => showPreviewPopup(threadRef, popupTabId, "floating")}
466 className="size-full"
467 />
468 </div>
469 ) : (
470 <>
471 <BrowserSurfaceSlot
472 tabId={runtimeTabId}
473 visible={Boolean(desktopOverlay?.hasWebContents) && !loadFailed}
474 cornerRadius={PREVIEW_MINI_PLAYER_CORNER_RADIUS}
475 zIndex={PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX}
476 fitSourceContent
477 layoutVersion={`${frame.x}:${frame.y}`}
478 className="absolute inset-0"
479 />
480 {loadFailed ? (
481 <div className="pointer-events-auto absolute inset-0 z-[48] overflow-hidden rounded-[inherit]">
482 <PreviewUnreachable
483 url={loadFailed.url}
484 code={loadFailed.code}
485 description={loadFailed.description}
486 onReload={() => void previewBridge?.refresh(runtimeTabId)}
487 />
488 </div>
489 ) : !desktopOverlay?.hasWebContents ? (
490 <div className="pointer-events-none absolute inset-0 z-[49] flex items-center justify-center rounded-[inherit] bg-muted text-xs text-muted-foreground">
491 <T>Reconnecting preview…</T>
492 </div>
493 ) : null}
494 </>
495 )
496 }
497 </MiniPlayerShell>
498 );
500​
501function DeviceMiniPlayer({
502 threadRef,
503 source,
504 miniPlayer,
505}: Props & { readonly source: Extract<PreviewMiniPlayerSource, { kind: "device" }> }) {
506 const gt = useGT();
507 const { state: deviceState } = useDeviceState(threadRef.environmentId);
508 const viewId = miniPlayerDeviceViewId(threadRef, source);
509 const screen = useAtomValue(deviceStreamScreenAtom(viewId));
510 const sourceSize = resolveDeviceMiniPlayerSourceSize(source.platform, screen);
511 const device = deviceState.devices.find(
512 (entry) => entry.hostId === source.hostId && entry.id === source.deviceId,
513 );
514 const host = deviceState.hosts.find((entry) => entry.id === source.hostId);
515 const hostLabel = host?.label ?? gt("Device host");
516 const cornerRadius = (player: PreviewMiniPlayerSize) =>
517 resolveDeviceMiniPlayerCornerRadius(source.platform, player);
518​
519 const openInPanel = () => {
520 usePreviewMiniPlayerStore.getState().close(threadRef);
521 useRightPanelStore.getState().openDevice(threadRef, {
522 hostId: source.hostId,
523 deviceId: source.deviceId,
524 platform: source.platform,
525 name: source.name,
526 });
527 };
528​
529 return (
530 <MiniPlayerShell
531 threadRef={threadRef}
532 miniPlayer={miniPlayer}
533 sourceSize={sourceSize}
534 label={gt("Floating device preview")}
535 onOpenInPanel={openInPanel}
536 cornerRadius={cornerRadius}
537 >
538 {() => (
539 <div
540 className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit]"
541 style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}
542 >
543 <DeviceStreamView
544 environmentId={threadRef.environmentId}
545 platform={source.platform}
546 deviceId={source.deviceId}
547 hostId={source.hostId}
548 deviceName={device?.name ?? source.name}
549 deviceDescription={`${hostLabel} · ${device?.version ?? source.platform}`}
550 visible
551 viewId={viewId}
552 serveSimOnly={host?.kind === "simlock"}
553 />
554 </div>
555 )}
556 </MiniPlayerShell>
557 );
559​
560/** Match native clipping and DOM radii to align their separately composited edges. */
561function MiniPlayerShell({
562 threadRef,
563 miniPlayer,
564 sourceSize,
565 label,
566 onOpenInPanel,
567 pillActions,
568 recording = false,
569 cornerRadius = frameCornerRadius,
570 children,
571}: {
572 readonly threadRef: ScopedThreadRef;
573 readonly miniPlayer: PreviewMiniPlayerState;
574 readonly sourceSize: PreviewMiniPlayerSize;
575 readonly label: string;
576 /** Omitted for sources that have no panel, such as the computer card. */
577 readonly onOpenInPanel?: () => void;
578 readonly pillActions?: ReactNode;
579 readonly recording?: boolean;
580 readonly cornerRadius?: (frame: PreviewMiniPlayerSize) => number;
581 readonly children: (frame: PreviewMiniPlayerFrame) => ReactNode;
582}) {
583 const gt = useGT();
584 const canvas = useChatCanvas();
585 const gestureRef = useRef<PreviewMiniPlayerGesture | null>(null);
586 const captureRef = useRef<HTMLElement | null>(null);
587 // Touch toggles the pill after the tap's click so that click cannot land on the newly opened pill.
588 const [pillOpen, setPillOpen] = useState(false);
589 const handleTappedRef = useRef(false);
590 const handleRef = useRef<HTMLDivElement | null>(null);
591 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document pointerdown listener closes the open pill on an outside press
592 useEffect(() => {
593 if (!pillOpen) return;
594 const dismiss = (event: PointerEvent) => {
595 if (event.target instanceof Node && handleRef.current?.contains(event.target)) return;
596 setPillOpen(false);
597 };
598 document.addEventListener("pointerdown", dismiss, true);
599 return () => document.removeEventListener("pointerdown", dismiss, true);
600 }, [pillOpen]);
601 const container = canvas?.container ?? null;
602 const sourceKey = previewMiniPlayerSourceKey(miniPlayer.source);
603 const heldSourceKey = streamedSourceKey(threadRef, sourceKey);
604 const frame = canvas?.previewKey === sourceKey ? canvas.layout.frame : null;
605​
606 const radius = frame ? cornerRadius(frame) : PREVIEW_MINI_PLAYER_CORNER_RADIUS;
607 const pillInset = Math.max(8, Math.round(radius * 0.55));
608​
609 const close = () => {
610 usePreviewMiniPlayerStore.getState().close(threadRef);
611 };
612​
613 /** Every way a gesture stops comes through here; returns the gesture it ended. */
614 const finishGesture = () => {
615 const gesture = gestureRef.current;
616 if (!gesture) return null;
617 gestureRef.current = null;
618 handleTappedRef.current = false;
619 const handle = captureRef.current;
620 captureRef.current = null;
621 if (handle?.hasPointerCapture(gesture.pointerId)) {
622 handle.releasePointerCapture(gesture.pointerId);
623 }
624 if (gesture.direction === null) return gesture;
625 useHeldSourceSize.setState((state) => (state?.key === heldSourceKey ? null : state), true);
626 const settled =
627 frame && container
628 ? settlePreviewMiniPlayerResize({
629 frame,
630 direction: gesture.direction,
631 held: gesture.source,
632 source: sourceSize,
633 container,
634 })
635 : null;
636 if (settled) {
637 usePreviewMiniPlayerStore
638 .getState()
639 .resize(threadRef, sourceKey, settled.width, { x: settled.x, y: settled.y });
640 }
641 return gesture;
642 };
643 const endInterruptedGesture = useEffectEvent(() => {
644 finishGesture();
645 });
646 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window blur ends a gesture whose release went to another window, and unmount ends one in progress
647 useEffect(() => {
648 window.addEventListener("blur", endInterruptedGesture);
649 return () => {
650 window.removeEventListener("blur", endInterruptedGesture);
651 useHeldSourceSize.setState((state) => (state?.key === heldSourceKey ? null : state), true);
652 };
653 }, [heldSourceKey]);
654​
655 const beginGesture = (
656 event: ReactPointerEvent<HTMLElement>,
657 direction: BrowserViewportResizeDirection | null,
658 ) => {
659 if (event.button !== 0 || !frame) return;
660 finishGesture();
661 gestureRef.current = {
662 pointerId: event.pointerId,
663 pointerType: event.pointerType,
664 pointerX: event.clientX,
665 pointerY: event.clientY,
666 frame,
667 direction,
668 source: sourceSize,
669 moved: false,
670 };
671 captureRef.current = event.currentTarget;
672 if (direction !== null) {
673 useHeldSourceSize.setState({ key: heldSourceKey, source: sourceSize }, true);
674 }
675 event.currentTarget.setPointerCapture(event.pointerId);
676 event.preventDefault();
677 event.stopPropagation();
678 };
679​
680 const handlePointerMove = (event: ReactPointerEvent<HTMLElement>) => {
681 const gesture = gestureRef.current;
682 if (!gesture || !container) return;
683 const step = stepPreviewMiniPlayerGesture(gesture, event, container);
684 if (step.kind === "ignore") return;
685 if (step.kind === "end") {
686 finishGesture();
687 return;
688 }
689 if (!gesture.moved) gestureRef.current = { ...gesture, moved: true };
690 const store = usePreviewMiniPlayerStore.getState();
691 if (step.kind === "move") {
692 store.move(threadRef, sourceKey, step.position);
693 return;
694 }
695 store.resize(threadRef, sourceKey, step.frame.width, { x: step.frame.x, y: step.frame.y });
696 };
697​
698 const endGesture = (event: ReactPointerEvent<HTMLElement>) => {
699 if (gestureRef.current?.pointerId !== event.pointerId) return;
700 const gesture = finishGesture();
701 handleTappedRef.current =
702 event.type === "pointerup" &&
703 gesture?.direction === null &&
704 gesture.pointerType === "touch" &&
705 !gesture.moved;
706 };
707​
708 // Capture can go without a release or cancel: the handle is replaced, or the platform takes it.
709 const handleLostCapture = (event: ReactPointerEvent<HTMLElement>) => {
710 if (
711 gestureRef.current?.pointerId === event.pointerId &&
712 captureRef.current === event.currentTarget
713 ) {
714 finishGesture();
715 }
716 };
717​
718 return (
719 <div className="pointer-events-none absolute inset-0">
720 {frame ? (
721 <section
722 aria-label={label}
723 data-preview-mini-player={sourceKey}
724 className="pointer-events-none absolute select-none"
725 style={{
726 left: frame.x,
727 top: frame.y,
728 width: frame.width,
729 height: frame.height,
730 borderRadius: radius,
731 }}
732 >
733 <div
734 ref={handleRef}
735 data-pill-open={pillOpen ? "" : undefined}
736 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"
737 style={{ right: pillInset, top: pillInset }}
738 onPointerDown={(event) => beginGesture(event, null)}
739 onPointerMove={handlePointerMove}
740 onPointerUp={endGesture}
741 onPointerCancel={endGesture}
742 onLostPointerCapture={handleLostCapture}
743 onClick={() => {
744 if (!handleTappedRef.current) return;
745 handleTappedRef.current = false;
746 setPillOpen((open) => !open);
747 }}
748 >
749 <div
750 role={recording ? "status" : undefined}
751 aria-label={recording ? gt("Recording preview") : undefined}
752 aria-hidden={!recording}
753 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"
754 >
755 <span
756 className={cn(
757 "block size-2 rounded-full shadow-sm ring-1 ring-background/70",
758 recording
759 ? "bg-destructive motion-safe:animate-status-pulse"
760 : "bg-foreground/25",
761 )}
762 />
763 </div>
764 <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">
765 {recording ? (
766 <span aria-hidden className="flex size-6 shrink-0 items-center justify-center">
767 <span className="size-2 rounded-full bg-destructive motion-safe:animate-status-pulse" />
768 </span>
769 ) : null}
770 {onOpenInPanel ? (
771 <Tooltip>
772 <TooltipTrigger
773 render={
774 <Button
775 variant="ghost"
776 size="icon-xs"
777 aria-label={gt("Open preview in right panel")}
778 onPointerDown={(event) => event.stopPropagation()}
779 onClick={onOpenInPanel}
780 />
781 }
782 >
783 <PanelRightIcon />
784 </TooltipTrigger>
785 <TooltipPopup side="top">
786 <T>Open in right panel</T>
787 </TooltipPopup>
788 </Tooltip>
789 ) : null}
790 {pillActions}
791 <Tooltip>
792 <TooltipTrigger
793 render={
794 <Button
795 variant="ghost"
796 size="icon-xs"
797 aria-label={gt("Close floating preview")}
798 onPointerDown={(event) => event.stopPropagation()}
799 onClick={close}
800 />
801 }
802 >
803 <XIcon />
804 </TooltipTrigger>
805 <TooltipPopup side="top">
806 <T>Close floating preview</T>
807 </TooltipPopup>
808 </Tooltip>
809 </div>
810 </div>
811​
812 <div className="absolute inset-0 z-[47] rounded-[inherit] bg-muted shadow-2xl/35" />
813 {children(frame)}
814 <div className="pointer-events-none absolute inset-0 z-[49] rounded-[inherit] ring-1 ring-inset ring-border/80" />
815 {RESIZE_HANDLES.map(({ direction, className }) => (
816 <div
817 key={direction}
818 role="presentation"
819 data-preview-mini-player-resize={direction}
820 className={cn("pointer-events-auto absolute z-[49] touch-none", className)}
821 onPointerDown={(event) => beginGesture(event, direction)}
822 onPointerMove={handlePointerMove}
823 onPointerUp={endGesture}
824 onPointerCancel={endGesture}
825 onLostPointerCapture={handleLostCapture}
826 />
827 ))}
828 </section>
829 ) : null}
830 </div>
831 );