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