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

HtmlRenderFrame.tsx

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