Open History to see the last commit
1import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
2import {
3 HTML_RENDER_COLUMN_WIDTH,
4 htmlRenderFileName,
5 htmlRenderFrameHeight,
6 type HtmlRenderReference,
7} from "@t3tools/shared/htmlRender";
8import { Maximize2Icon } from "lucide-react";
9import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
10
11import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
12
13import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
14import { Button } from "../ui/button";
15import { toastManager } from "../ui/toast";
16import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
17import { HtmlRenderDialog } from "./HtmlRenderDialog";
18import { observeResize } from "~/lib/observeResize";
19
20// A frame may load its URL a little after mounting.
21const MIN_URL_LIFE_MS = 5 * 60_000;
22
23/**
24 * An agent's HTML render inline in the thread: the page itself on the thread's
25 * own background, at the server's measured height for this width until the
26 * page reports its own. Loading and failure hold the same box so nothing below
27 * it moves.
28 */
29export function HtmlRenderFrame(props: {
30 readonly environmentId: EnvironmentId;
31 readonly htmlRender: HtmlRenderReference;
32 readonly threadRef: ScopedThreadRef | undefined;
33 readonly onFullscreenChange?: (fullscreen: boolean) => void;
34}) {
35 const { attachmentId, title } = props.htmlRender;
36 // The frame takes the page's measured height at its own width, read before
37 // first paint so the reserved box is already the right size.
38 const boxRef = useRef<HTMLDivElement>(null);
39 const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
40 useLayoutEffect(() => {
41 const box = boxRef.current;
42 if (!box) return;
43 setWidth(box.clientWidth);
44 return observeResize(box, ([entry]) => {
45 if (entry) setWidth(entry.contentRect.width);
46 });
47 }, []);
48 // Client fonts can wrap a page taller than the server measured it; a frame
49 // left short would scroll inside the thread and take the reader's scroll.
50 const [contentHeight, setContentHeight] = useState<number>();
51 const height = htmlRenderFrameHeight(props.htmlRender, width, contentHeight);
52 const fileName = htmlRenderFileName(title);
53 const resource = useMemo(
54 () => ({
55 _tag: "attachment" as const,
56 attachmentId,
57 fileName,
58 mimeType: "text/html",
59 disposition: "inline" as const,
60 }),
61 [attachmentId, fileName],
62 );
63 // A cached URL with life left is reused, so the browser's cache serves the
64 // page again; one near expiry is minted afresh, since a frame cannot report a
65 // failed load. The page keeps its first URL for its lifetime.
66 const [src, setSrc] = useState<string | null>(null);
67 const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
68 const { onFullscreenChange } = props;
69 useEffect(() => {
70 if (expandedSrc === null) return;
71 onFullscreenChange?.(true);
72 return () => onFullscreenChange?.(false);
73 }, [expandedSrc, onFullscreenChange]);
74 const [failed, setFailed] = useState(false);
75 const assetUrl = useAssetUrlState(src === null ? props.environmentId : null, resource);
76 const cachedUrl = assetUrl._tag === "Success" ? assetUrl.url : null;
77 const cachedExpiresAt = assetUrl._tag === "Success" ? assetUrl.expiresAt : 0;
78 const cacheFailed = assetUrl._tag === "Failure";
79 const refresh = useAssetUrlRefresh(props.environmentId, resource);
80 // At most one mint per mount: expiry is server time and the check uses the
81 // client clock, so a skewed clock must not mint again on every update.
82 const minting = useRef(false);
83 useEffect(() => {
84 if (src !== null || minting.current) return;
85 if (cacheFailed) {
86 // oxlint-disable-next-line react/set-state-in-effect -- Mirrors the cached URL's failure.
87 setFailed(true);
88 return;
89 }
90 if (cachedUrl === null) return;
91 if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
92 setSrc(cachedUrl);
93 return;
94 }
95 minting.current = true;
96 void refresh().then(
97 (url) => (url === null ? setFailed(true) : setSrc(url)),
98 () => setFailed(true),
99 );
100 }, [cacheFailed, cachedExpiresAt, cachedUrl, refresh, src]);
101
102 return (
103 <div ref={boxRef} className="group/html-render relative" style={{ height }}>
104 {src !== null ? (
105 <>
106 <HtmlRenderDocument
107 src={src}
108 title={title}
109 threadRef={props.threadRef}
110 className="block size-full"
111 onContentHeight={setContentHeight}
112 />
113 <div className="absolute end-2 top-2 flex gap-1 opacity-0 transition-opacity duration-150 focus-within:opacity-100 group-hover/html-render:opacity-100 pointer-coarse:opacity-100">
114 <Tooltip>
115 <TooltipTrigger
116 render={
117 <Button
118 aria-label="Open full screen"
119 size="icon-xs"
120 variant="glass"
121 onClick={async () => {
122 const url = await refresh().catch(() => null);
123 if (url !== null) setExpandedSrc(url);
124 else
125 toastManager.add({
126 type: "error",
127 title: "Page unavailable",
128 description: "Reconnect to the environment and try again.",
129 });
130 }}
131 />
132 }
133 >
134 <Maximize2Icon className="size-3.5" />
135 </TooltipTrigger>
136 <TooltipPopup side="left">Open full screen</TooltipPopup>
137 </Tooltip>
138 </div>
139 {expandedSrc !== null ? (
140 <HtmlRenderDialog
141 src={expandedSrc}
142 title={title}
143 threadRef={props.threadRef}
144 onClose={() => setExpandedSrc(null)}
145 />
146 ) : null}
147 </>
148 ) : failed ? (
149 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
150 Unable to load {title}
151 </p>
152 ) : null}
153 </div>
154 );
155}