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

ThreadPreviewMiniPlayer.tsx

336 lines12.4 KB

1"use client";
2​
3import type { ScopedThreadRef } from "@t3tools/contracts";
4import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
5import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef } from "react";
6​
7import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
8import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
9import { Button } from "~/components/ui/button";
10import { toastManager } from "~/components/ui/toast";
11import { useThreadPreviewState } from "~/previewStateStore";
12import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
13import { useRightPanelStore } from "~/rightPanelStore";
14​
15import { previewBridge } from "./previewBridge";
16import {
17 clampPreviewMiniPlayerPosition,
18 clampPreviewMiniPlayerSize,
19 defaultPreviewMiniPlayerPosition,
20 PREVIEW_MINI_PLAYER_DEFAULT_SIZE,
21} from "./previewMiniPlayerLayout";
22​
23/**
24 * Where a freshly opened player should land: under the inline thread-details
25 * card when that panel is open (it owns the top-right corner), otherwise the
26 * top-right CSS placement the element already has.
27 */
28function initialPreviewMiniPlayerPosition(root: HTMLElement, parent: HTMLElement) {
29 const fallback = { x: root.offsetLeft, y: root.offsetTop };
30 const card = root
31 .closest('[data-thread-details-inline-reserved="true"]')
32 ?.querySelector('[data-thread-details-panel="inline"] [data-thread-details-card]');
33 if (!(card instanceof HTMLElement)) return fallback;
34 const cardRect = card.getBoundingClientRect();
35 return defaultPreviewMiniPlayerPosition({
36 fallback,
37 parentRect: parent.getBoundingClientRect(),
38 playerWidth: root.offsetWidth,
39 detailsCardRect: { right: cardRect.right, bottom: cardRect.bottom },
40 });
42​
43interface DragState {
44 readonly pointerId: number;
45 readonly pointerX: number;
46 readonly pointerY: number;
47 readonly playerX: number;
48 readonly playerY: number;
50​
51interface ResizeState {
52 readonly pointerId: number;
53 readonly pointerX: number;
54 readonly pointerY: number;
55 readonly width: number;
56 readonly height: number;
58​
59interface Props {
60 readonly threadRef: ScopedThreadRef;
61 readonly tabId: string;
62 readonly bottomInset: number;
64​
65export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props) {
66 const rootRef = useRef<HTMLElement | null>(null);
67 const dragRef = useRef<DragState | null>(null);
68 const resizeRef = useRef<ResizeState | null>(null);
69 const miniPlayer = usePreviewMiniPlayerStore((state) =>
70 selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),
71 );
72 const previewState = useThreadPreviewState(threadRef);
73 const snapshot = previewState.sessions[tabId] ?? null;
74 const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
75 const desktopOverlay = previewState.desktopByTabId[tabId] ?? null;
76 const position = miniPlayer?.tabId === tabId ? miniPlayer.position : null;
77 const size =
78 miniPlayer?.tabId === tabId && miniPlayer.size
79 ? miniPlayer.size
80 : PREVIEW_MINI_PLAYER_DEFAULT_SIZE;
81 const close = () => {
82 usePreviewMiniPlayerStore.getState().close(threadRef);
83 };
84​
85 const openInPanel = () => {
86 usePreviewMiniPlayerStore.getState().close(threadRef);
87 useRightPanelStore.getState().openBrowser(threadRef, tabId);
88 };
89​
90 const toggleNativePictureInPicture = () => {
91 if (!previewBridge) return;
92 const operation = desktopOverlay?.pictureInPicture
93 ? previewBridge.pictureInPicture.close
94 : previewBridge.pictureInPicture.open;
95 void operation(runtimeTabId).catch((error) => {
96 toastManager.add({
97 type: "error",
98 title: "Unable to update popped-out preview",
99 description: error instanceof Error ? error.message : "An error occurred.",
100 });
101 });
102 };
103​
104 useLayoutEffect(() => {
105 const clampAndMove = () => {
106 const root = rootRef.current;
107 const parent = root?.offsetParent;
108 if (!root || !(parent instanceof HTMLElement)) return;
109 const nextSize = clampPreviewMiniPlayerSize(
110 { width: root.offsetWidth, height: root.offsetHeight },
111 { width: parent.clientWidth, height: parent.clientHeight },
112 bottomInset,
113 );
114 usePreviewMiniPlayerStore.getState().resize(threadRef, tabId, nextSize);
115 const next = clampPreviewMiniPlayerPosition(
116 position ?? initialPreviewMiniPlayerPosition(root, parent),
117 { width: parent.clientWidth, height: parent.clientHeight },
118 nextSize,
119 bottomInset,
120 );
121 usePreviewMiniPlayerStore.getState().move(threadRef, tabId, next);
122 };
123 clampAndMove();
124 const root = rootRef.current;
125 const parent = root?.offsetParent;
126 if (!root || !(parent instanceof HTMLElement) || typeof ResizeObserver === "undefined") {
127 return;
128 }
129 const observer = new ResizeObserver(clampAndMove);
130 observer.observe(root);
131 observer.observe(parent);
132 return () => observer.disconnect();
133 }, [bottomInset, position, tabId, threadRef]);
134​
135 const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
136 if (event.button !== 0) return;
137 const root = rootRef.current;
138 const parent = root?.offsetParent;
139 if (!root || !(parent instanceof HTMLElement)) return;
140 const rootRect = root.getBoundingClientRect();
141 const parentRect = parent.getBoundingClientRect();
142 dragRef.current = {
143 pointerId: event.pointerId,
144 pointerX: event.clientX,
145 pointerY: event.clientY,
146 playerX: rootRect.left - parentRect.left,
147 playerY: rootRect.top - parentRect.top,
148 };
149 event.currentTarget.setPointerCapture(event.pointerId);
150 event.preventDefault();
151 };
152​
153 const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
154 const drag = dragRef.current;
155 const root = rootRef.current;
156 const parent = root?.offsetParent;
157 if (!drag || drag.pointerId !== event.pointerId || !root || !(parent instanceof HTMLElement)) {
158 return;
159 }
160 const next = clampPreviewMiniPlayerPosition(
161 {
162 x: drag.playerX + event.clientX - drag.pointerX,
163 y: drag.playerY + event.clientY - drag.pointerY,
164 },
165 { width: parent.clientWidth, height: parent.clientHeight },
166 { width: root.offsetWidth, height: root.offsetHeight },
167 bottomInset,
168 );
169 usePreviewMiniPlayerStore.getState().move(threadRef, tabId, next);
170 };
171​
172 const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
173 if (dragRef.current?.pointerId !== event.pointerId) return;
174 dragRef.current = null;
175 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
176 event.currentTarget.releasePointerCapture(event.pointerId);
177 }
178 };
179​
180 const handleResizePointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {
181 if (event.button !== 0) return;
182 const root = rootRef.current;
183 if (!root) return;
184 resizeRef.current = {
185 pointerId: event.pointerId,
186 pointerX: event.clientX,
187 pointerY: event.clientY,
188 width: root.offsetWidth,
189 height: root.offsetHeight,
190 };
191 event.currentTarget.setPointerCapture(event.pointerId);
192 event.preventDefault();
193 event.stopPropagation();
194 };
195​
196 const handleResizePointerMove = (event: ReactPointerEvent<HTMLButtonElement>) => {
197 const resize = resizeRef.current;
198 const root = rootRef.current;
199 const parent = root?.offsetParent;
200 if (
201 !resize ||
202 resize.pointerId !== event.pointerId ||
203 !root ||
204 !(parent instanceof HTMLElement)
205 ) {
206 return;
207 }
208 const nextSize = clampPreviewMiniPlayerSize(
209 {
210 width: resize.width + event.clientX - resize.pointerX,
211 height: resize.height + event.clientY - resize.pointerY,
212 },
213 { width: parent.clientWidth, height: parent.clientHeight },
214 bottomInset,
215 );
216 usePreviewMiniPlayerStore.getState().resize(threadRef, tabId, nextSize);
217 const nextPosition = clampPreviewMiniPlayerPosition(
218 position ?? { x: root.offsetLeft, y: root.offsetTop },
219 { width: parent.clientWidth, height: parent.clientHeight },
220 nextSize,
221 bottomInset,
222 );
223 usePreviewMiniPlayerStore.getState().move(threadRef, tabId, nextPosition);
224 };
225​
226 const endResize = (event: ReactPointerEvent<HTMLButtonElement>) => {
227 if (resizeRef.current?.pointerId !== event.pointerId) return;
228 resizeRef.current = null;
229 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
230 event.currentTarget.releasePointerCapture(event.pointerId);
231 }
232 };
233​
234 if (!snapshot || miniPlayer?.tabId !== tabId) return null;
235​
236 return (
237 <section
238 ref={rootRef}
239 aria-label="Floating browser preview"
240 data-preview-mini-player={tabId}
241 className="pointer-events-none absolute select-none"
242 style={
243 position
244 ? { left: position.x, top: position.y, width: size.width, height: size.height }
245 : {
246 right: 16,
247 top: 16,
248 width: size.width,
249 height: size.height,
250 }
251 }
252 >
253 <div className="group pointer-events-auto absolute right-2 top-2 z-[34] size-3">
254 <div
255 aria-hidden="true"
256 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"
257 />
258 <div
259 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"
260 onPointerDown={handlePointerDown}
261 onPointerMove={handlePointerMove}
262 onPointerUp={endDrag}
263 onPointerCancel={endDrag}
264 >
265 <Button
266 variant="ghost"
267 size="icon-xs"
268 aria-label="Open preview in right panel"
269 title="Open in right panel"
270 onPointerDown={(event) => event.stopPropagation()}
271 onClick={openInPanel}
272 >
273 <PanelRightIcon />
274 </Button>
275 <Button
276 variant={desktopOverlay?.pictureInPicture ? "secondary" : "ghost"}
277 size="icon-xs"
278 aria-label={
279 desktopOverlay?.pictureInPicture
280 ? "Close popped-out preview"
281 : "Pop preview into separate window"
282 }
283 title={
284 desktopOverlay?.pictureInPicture
285 ? "Close separate window"
286 : "Pop into separate window"
287 }
288 disabled={!desktopOverlay?.hasWebContents}
289 onPointerDown={(event) => event.stopPropagation()}
290 onClick={toggleNativePictureInPicture}
291 >
292 <PictureInPicture2 />
293 </Button>
294 <Button
295 variant="ghost"
296 size="icon-xs"
297 aria-label="Close floating preview"
298 title="Close floating preview"
299 onPointerDown={(event) => event.stopPropagation()}
300 onClick={close}
301 >
302 <XIcon />
303 </Button>
304 </div>
305 </div>
306​
307 <div className="relative h-full min-h-0">
308 <div className="absolute inset-0 z-[29] rounded-xl bg-muted shadow-2xl/35" />
309 <BrowserSurfaceSlot
310 tabId={runtimeTabId}
311 visible={Boolean(desktopOverlay?.hasWebContents)}
312 cornerRadius={12}
313 fitSourceContent
314 layoutVersion={position ? `${position.x}:${position.y}` : `initial:${bottomInset}`}
315 className="absolute inset-0"
316 />
317 <div className="pointer-events-none absolute inset-0 z-[31] rounded-xl ring-1 ring-inset ring-border/80" />
318 {!desktopOverlay?.hasWebContents ? (
319 <div className="pointer-events-none absolute inset-0 z-[32] flex items-center justify-center rounded-xl bg-muted text-xs text-muted-foreground">
320 Reconnecting preview…
321 </div>
322 ) : null}
323 <button
324 type="button"
325 aria-label="Resize floating preview"
326 title="Resize floating preview"
327 className="pointer-events-auto absolute bottom-0 right-0 z-[33] size-5 cursor-nwse-resize rounded-br-xl after:absolute after:bottom-1 after:right-1 after:size-2 after:border-b after:border-r after:border-foreground/45"
328 onPointerDown={handleResizePointerDown}
329 onPointerMove={handleResizePointerMove}
330 onPointerUp={endResize}
331 onPointerCancel={endResize}
332 />
333 </div>
334 </section>
335 );