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

HtmlRenderFrame.tsx

240 lines8.5 KB

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