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

BrowserSurfaceSlot.tsx

45 lines1.3 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 className?: string;
11}) {
12 const { tabId, visible, className } = props;
13 const elementRef = useRef<HTMLDivElement | null>(null);
14​
15 useLayoutEffect(() => {
16 const element = elementRef.current;
17 if (!element) return;
18 const lease = acquireBrowserSurface(tabId);
19 const update = () => {
20 const rect = element.getBoundingClientRect();
21 lease.present(
22 {
23 x: Math.round(rect.x),
24 y: Math.round(rect.y),
25 width: Math.max(1, Math.round(rect.width)),
26 height: Math.max(1, Math.round(rect.height)),
27 },
28 visible && rect.width > 0 && rect.height > 0,
29 );
30 };
31 update();
32 const observer = new ResizeObserver(update);
33 observer.observe(element);
34 window.addEventListener("resize", update);
35 window.addEventListener("scroll", update, true);
36 return () => {
37 observer.disconnect();
38 window.removeEventListener("resize", update);
39 window.removeEventListener("scroll", update, true);
40 lease.release();
41 };
42 }, [tabId, visible]);
43​
44 return <div ref={elementRef} className={className} data-browser-surface-slot={tabId} />;