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 htmlRenderOutlineBoxes,
7 type HtmlRenderOutlineBox,
8 type HtmlRenderReference,
9} from "@t3tools/shared/htmlRender";
10import { Maximize2Icon } from "lucide-react";
11import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
12
13import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
14import { cn } from "~/lib/utils";
15
16import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
17import { Button } from "../ui/button";
18import { Skeleton } from "../ui/skeleton";
19import { toastManager } from "../ui/toast";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { HtmlRenderDialog } from "./HtmlRenderDialog";
22import { observeResize } from "~/lib/observeResize";
23
24// A frame may load its URL a little after mounting.
25const MIN_URL_LIFE_MS = 5 * 60_000;
26
27/**
28 * An agent's HTML render inline in the thread: the page itself on the thread's
29 * own background, at the server's measured height for this width until the
30 * page reports its own. Loading and failure hold the same box so nothing below
31 * it moves.
32 */
33export function HtmlRenderFrame(props: {
34 readonly environmentId: EnvironmentId;
35 readonly htmlRender: HtmlRenderReference;
36 readonly threadRef: ScopedThreadRef | undefined;
37 readonly onFullscreenChange?: (fullscreen: boolean) => void;
38}) {
39 const { attachmentId, title } = props.htmlRender;
40 // The frame takes the page's measured height at its own width, read before
41 // first paint so the reserved box is already the right size.
42 const boxRef = useRef<HTMLDivElement>(null);
43 const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
44 useLayoutEffect(() => {
45 const box = boxRef.current;
46 if (!box) return;
47 setWidth(box.clientWidth);
48 return observeResize(box, ([entry]) => {
49 if (entry) setWidth(entry.contentRect.width);
50 });
51 }, []);
52 // Client fonts can wrap a page taller than the server measured it; a frame
53 // left short would scroll inside the thread and take the reader's scroll.
54 const [contentHeight, setContentHeight] = useState<number>();
55 const height = htmlRenderFrameHeight(props.htmlRender, width, contentHeight);
56 const fileName = htmlRenderFileName(title);
57 const resource = useMemo(
58 () => ({
59 _tag: "attachment" as const,
60 attachmentId,
61 fileName,
62 mimeType: "text/html",
63 disposition: "inline" as const,
64 }),
65 [attachmentId, fileName],
66 );
67 // A cached URL with life left is reused, so the browser's cache serves the
68 // page again; one near expiry is minted afresh, since a frame cannot report a
69 // failed load. The page keeps its first URL for its lifetime.
70 const [src, setSrc] = useState<string | null>(null);
71 // Full screen reuses the inline URL while it has life left, so the page
72 // comes from the browser's cache instead of a new mint and download.
73 const srcExpiresAt = useRef(0);
74 const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
75 // The page stays hidden behind a skeleton until it reports its content.
76 const [ready, setReady] = useState(false);
77 const showPage = useCallback(() => setReady(true), []);
78 const fitPage = useCallback((contentHeight: number) => {
79 setContentHeight(contentHeight);
80 setReady(true);
81 }, []);
82 const { onFullscreenChange } = props;
83 useEffect(() => {
84 if (expandedSrc === null) return;
85 onFullscreenChange?.(true);
86 return () => onFullscreenChange?.(false);
87 }, [expandedSrc, onFullscreenChange]);
88 const [failed, setFailed] = useState(false);
89 const assetUrl = useAssetUrlState(src === null ? props.environmentId : null, resource);
90 const cachedUrl = assetUrl._tag === "Success" ? assetUrl.url : null;
91 const cachedExpiresAt = assetUrl._tag === "Success" ? assetUrl.expiresAt : 0;
92 const cacheFailed = assetUrl._tag === "Failure";
93 const refresh = useAssetUrlRefresh(props.environmentId, resource);
94 // At most one mint per mount: expiry is server time and the check uses the
95 // client clock, so a skewed clock must not mint again on every update.
96 const minting = useRef(false);
97 useEffect(() => {
98 if (src !== null || minting.current) return;
99 if (cacheFailed) {
100 // oxlint-disable-next-line react/set-state-in-effect -- Mirrors the cached URL's failure.
101 setFailed(true);
102 return;
103 }
104 if (cachedUrl === null) return;
105 if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
106 srcExpiresAt.current = cachedExpiresAt;
107 setSrc(cachedUrl);
108 return;
109 }
110 minting.current = true;
111 void refresh().then(
112 (url) => (url === null ? setFailed(true) : setSrc(url)),
113 () => setFailed(true),
114 );
115 }, [cacheFailed, cachedExpiresAt, cachedUrl, refresh, src]);
116
117 return (
118 <div ref={boxRef} className="group/html-render relative" style={{ height }}>
119 {!ready && !failed ? (
120 <HtmlRenderSkeleton
121 title={title}
122 height={height}
123 outline={htmlRenderOutlineBoxes(props.htmlRender, width)}
124 />
125 ) : null}
126 {src !== null ? (
127 <>
128 <HtmlRenderDocument
129 src={src}
130 title={title}
131 threadRef={props.threadRef}
132 className={cn(
133 "block size-full motion-safe:transition-opacity motion-safe:duration-200",
134 !ready && "opacity-0",
135 )}
136 onContentHeight={fitPage}
137 onLoad={showPage}
138 onFullscreenChange={onFullscreenChange}
139 />
140 <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">
141 <Tooltip>
142 <TooltipTrigger
143 render={
144 <Button
145 aria-label="Open full screen"
146 size="icon-xs"
147 variant="glass"
148 onClick={async () => {
149 const url =
150 srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
151 ? src
152 : await refresh().catch(() => null);
153 if (url !== null) setExpandedSrc(url);
154 else
155 toastManager.add({
156 type: "error",
157 title: "Page unavailable",
158 description: "Reconnect to the environment and try again.",
159 });
160 }}
161 />
162 }
163 >
164 <Maximize2Icon className="size-3.5" />
165 </TooltipTrigger>
166 <TooltipPopup side="left">Open full screen</TooltipPopup>
167 </Tooltip>
168 </div>
169 {expandedSrc !== null ? (
170 <HtmlRenderDialog
171 src={expandedSrc}
172 title={title}
173 threadRef={props.threadRef}
174 onClose={() => setExpandedSrc(null)}
175 />
176 ) : null}
177 </>
178 ) : failed ? (
179 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
180 Unable to load {title}
181 </p>
182 ) : null}
183 </div>
184 );
185}
186
187// Without an outline: one heading, a line of text, and a chart-sized block,
188// the shape most pages take, repeated to fill the frame's reserved height.
189const SKELETON_SECTION_HEIGHT = 264;
190
191const OUTLINE_BOX_CLASS = {
192 media: "rounded-lg bg-muted-foreground/15",
193 text: "",
194 table: "",
195} as const;
196
197const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)";
198
199// Text lines and table rows are bars painted by one gradient per box, so a
200// long page costs one element per block rather than one per line.
201function outlineBoxStyle(box: HtmlRenderOutlineBox): React.CSSProperties {
202 const style: React.CSSProperties = {
203 left: box.x,
204 top: box.y,
205 width: box.width,
206 height: box.height,
207 };
208 if (box.kind !== "text" && box.kind !== "table") return style;
209 const step = box.height / box.lines;
210 const bar = Math.min(box.kind === "table" ? 12 : 10, step * 0.6);
211 const start = (step - bar) / 2;
212 return {
213 ...style,
214 backgroundImage: `repeating-linear-gradient(to bottom, transparent 0 ${start}px, ${OUTLINE_BAR} ${start}px ${start + bar}px, transparent ${start + bar}px ${step}px)`,
215 };
216}
217
218/**
219 * Holds the frame's place while the page loads: the page's own blocks when the
220 * server measured an outline, else a generic page shape. The outline pulses
221 * as one layer.
222 */
223function HtmlRenderSkeleton(props: {
224 readonly title: string;
225 readonly height: number;
226 readonly outline: ReadonlyArray<HtmlRenderOutlineBox>;
227}) {
228 if (props.outline.length > 0) {
229 return (
230 <div
231 role="status"
232 aria-label={`Loading ${props.title}`}
233 className="pointer-events-none absolute inset-0 overflow-hidden motion-safe:animate-skeleton"
234 >
235 {props.outline.map((box) => (
236 <div
237 key={`${box.kind}:${box.x}:${box.y}:${box.width}:${box.height}`}
238 className={cn("absolute", OUTLINE_BOX_CLASS[box.kind])}
239 style={outlineBoxStyle(box)}
240 />
241 ))}
242 </div>
243 );
244 }
245 const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT);
246 return (
247 <div
248 role="status"
249 aria-label={`Loading ${props.title}`}
250 className="pointer-events-none absolute inset-0 flex flex-col gap-6 overflow-hidden pt-1"
251 >
252 {Array.from({ length: sections }, (_, index) => (
253 <div key={index} className="flex shrink-0 flex-col gap-2">
254 <Skeleton className="h-4 w-2/5" />
255 <Skeleton className="h-3 w-3/5" />
256 <Skeleton shape="card" className="mt-2 h-40 w-full" />
257 </div>
258 ))}
259 </div>
260 );
261}