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