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

BrowserSurfaceSlot.tsx

88 lines2.9 KB

1"use client";
2​
3import { useLayoutEffect, useRef } from "react";
4​
5import { acquireBrowserSurface } from "./browserSurfaceStore";
6​
7export function BrowserSurfaceSlot(props: {
8 readonly tabId: string;
9 readonly visible: boolean;
10 readonly cornerRadius?: number;
11 readonly zIndex?: number;
12 readonly layoutVersion?: string | number;
13 readonly className?: string;
14 readonly fitSourceContent?: boolean;
15}) {
16 const {
17 tabId,
18 visible,
19 cornerRadius = 0,
20 zIndex = 30,
21 layoutVersion,
22 className,
23 fitSourceContent = false,
24 } = props;
25 const elementRef = useRef<HTMLDivElement | null>(null);
26 const presentationRef = useRef({ visible, cornerRadius, zIndex });
27 const updateRef = useRef<(() => void) | null>(null);
28​
29 useLayoutEffect(() => {
30 const element = elementRef.current;
31 if (!element) return;
32 let lease = acquireBrowserSurface(tabId, fitSourceContent);
33 const update = () => {
34 const rect = element.getBoundingClientRect();
35 const presentation = presentationRef.current;
36 const presented = lease.present(
37 {
38 x: Math.round(rect.x),
39 y: Math.round(rect.y),
40 width: Math.max(1, Math.round(rect.width)),
41 height: Math.max(1, Math.round(rect.height)),
42 },
43 presentation.visible && rect.width > 0 && rect.height > 0,
44 presentation.cornerRadius,
45 presentation.zIndex,
46 );
47 if (presentation.visible && !presented) {
48 lease.release();
49 lease = acquireBrowserSurface(tabId, fitSourceContent);
50 lease.present(
51 {
52 x: Math.round(rect.x),
53 y: Math.round(rect.y),
54 width: Math.max(1, Math.round(rect.width)),
55 height: Math.max(1, Math.round(rect.height)),
56 },
57 rect.width > 0 && rect.height > 0,
58 presentation.cornerRadius,
59 presentation.zIndex,
60 );
61 }
62 };
63 updateRef.current = update;
64 update();
65 const observer = new ResizeObserver(update);
66 observer.observe(element);
67 // Inline panels animate their outer width while keeping the content at
68 // full width. The slot moves without resizing, so measure on shell resizes too.
69 const panel = element.closest('[data-preview-panel-mode="inline"]');
70 if (panel) observer.observe(panel);
71 window.addEventListener("resize", update);
72 window.addEventListener("scroll", update, true);
73 return () => {
74 observer.disconnect();
75 window.removeEventListener("resize", update);
76 window.removeEventListener("scroll", update, true);
77 if (updateRef.current === update) updateRef.current = null;
78 lease.release();
79 };
80 }, [fitSourceContent, tabId]);
81​
82 useLayoutEffect(() => {
83 presentationRef.current = { visible, cornerRadius, zIndex };
84 updateRef.current?.();
85 }, [cornerRadius, layoutVersion, visible, zIndex]);
86​
87 return <div ref={elementRef} className={className} data-browser-surface-slot={tabId} />;