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

HtmlRenderFrame.tsx

149 lines5.7 KB

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, 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​
20const MIN_URL_LIFE_MS = 5 * 60_000;
21​
22export function HtmlRenderFrame(props: {
23 readonly environmentId: EnvironmentId;
24 readonly htmlRender: HtmlRenderReference;
25 readonly threadRef: ScopedThreadRef | undefined;
26 readonly onFullscreenChange?: (fullscreen: boolean) => void;
27}) {
28 const { attachmentId, title } = props.htmlRender;
29 const boxRef = useRef<HTMLDivElement>(null);
30 const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
31 useLayoutEffect(() => {
32 const box = boxRef.current;
33 if (!box) return;
34 setWidth(box.clientWidth);
35 return observeResize(box, ([entry]) => {
36 if (entry) setWidth(entry.contentRect.width);
37 });
38 }, []);
39 // Client fonts can wrap a page taller than the server measured it; a frame
40 // left short would scroll inside the thread and take the reader's scroll.
41 const [contentHeight, setContentHeight] = useState<number>();
42 const height = htmlRenderFrameHeight(props.htmlRender, width, contentHeight);
43 const fileName = htmlRenderFileName(title);
44 const resource = {
45 _tag: "attachment" as const,
46 attachmentId,
47 fileName,
48 mimeType: "text/html",
49 disposition: "inline" as const,
50 };
51 // A cached URL with life left is reused, so the browser's cache serves the
52 // page again; one near expiry is minted afresh, since a frame cannot report a
53 // failed load.
54 const [src, setSrc] = useState<string | null>(null);
55 const srcExpiresAt = useRef(0);
56 const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
57 const { onFullscreenChange } = props;
58 useEffect(() => {
59 if (expandedSrc === null) return;
60 onFullscreenChange?.(true);
61 return () => onFullscreenChange?.(false);
62 }, [expandedSrc, onFullscreenChange]);
63 const [failed, setFailed] = useState(false);
64 const assetUrl = useAssetUrlState(src === null ? props.environmentId : null, resource);
65 const cachedUrl = assetUrl._tag === "Success" ? assetUrl.url : null;
66 const cachedExpiresAt = assetUrl._tag === "Success" ? assetUrl.expiresAt : 0;
67 const cacheFailed = assetUrl._tag === "Failure";
68 const refresh = useAssetUrlRefresh(props.environmentId, resource);
69 // At most one mint per mount: expiry is server time and the check uses the
70 // client clock, so a skewed clock must not mint again on every update.
71 const minting = useRef(false);
72 useEffect(() => {
73 if (src !== null || minting.current) return;
74 if (cacheFailed) {
75 // oxlint-disable-next-line react/set-state-in-effect -- Mirrors the cached URL's failure.
76 setFailed(true);
77 return;
78 }
79 if (cachedUrl === null) return;
80 if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
81 srcExpiresAt.current = cachedExpiresAt;
82 setSrc(cachedUrl);
83 return;
84 }
85 minting.current = true;
86 void refresh().then(
87 (url) => (url === null ? setFailed(true) : setSrc(url)),
88 () => setFailed(true),
89 );
90 }, [cacheFailed, cachedExpiresAt, cachedUrl, refresh, src]);
91​
92 return (
93 <div ref={boxRef} className="group/html-render relative" style={{ height }}>
94 {src !== null ? (
95 <>
96 <HtmlRenderDocument
97 src={src}
98 title={title}
99 threadRef={props.threadRef}
100 className="block size-full"
101 onContentHeight={setContentHeight}
102 onFullscreenChange={onFullscreenChange}
103 />
104 <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">
105 <Tooltip>
106 <TooltipTrigger
107 render={
108 <Button
109 aria-label="Open full screen"
110 size="icon-xs"
111 variant="glass"
112 onClick={async () => {
113 const url =
114 srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
115 ? src
116 : await refresh().catch(() => null);
117 if (url !== null) setExpandedSrc(url);
118 else
119 toastManager.add({
120 type: "error",
121 title: "Page unavailable",
122 description: "Reconnect to the environment and try again.",
123 });
124 }}
125 />
126 }
127 >
128 <Maximize2Icon className="size-3.5" />
129 </TooltipTrigger>
130 <TooltipPopup side="left">Open full screen</TooltipPopup>
131 </Tooltip>
132 </div>
133 {expandedSrc !== null ? (
134 <HtmlRenderDialog
135 src={expandedSrc}
136 title={title}
137 threadRef={props.threadRef}
138 onClose={() => setExpandedSrc(null)}
139 />
140 ) : null}
141 </>
142 ) : failed ? (
143 <p className="flex size-full items-center justify-center text-muted-foreground text-xs">
144 Unable to load {title}
145 </p>
146 ) : null}
147 </div>
148 );