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