Skip to content

Commit 2803f84

Browse files
committed
perf(web): HTML renders load behind a skeleton and open full screen from cache
Inline renders show a skeleton until the page reports its content, then fade in. Full screen reuses the inline page URL while it has life left, so the page comes from the browser cache instead of a new mint and download.
1 parent f87dd14 commit 2803f84

3 files changed

Lines changed: 79 additions & 13 deletions

File tree

‎apps/web/src/components/chat/HtmlRenderDialog.test.tsx‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
1010
import { HtmlRenderDialog } from "./HtmlRenderDialog";
1111
import { HtmlRenderFrame } from "./HtmlRenderFrame";
1212

13-
const { refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({
13+
const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({
14+
cachedUrl: { lifeMs: 60 * 60_000 },
1415
refresh: vi.fn(),
1516
showError: vi.fn(),
1617
openLink: vi.fn(),
@@ -24,7 +25,7 @@ vi.mock("~/assets/assetUrls", () => ({
2425
useAssetUrlState: () => ({
2526
_tag: "Success",
2627
url: "https://environment.test/original.html",
27-
expiresAt: Date.now() + 60 * 60_000,
28+
expiresAt: Date.now() + cachedUrl.lifeMs,
2829
}),
2930
useAssetUrlRefresh: () => refresh,
3031
}));
@@ -50,6 +51,7 @@ beforeEach(async () => {
5051
},
5152
);
5253
refresh.mockReset();
54+
cachedUrl.lifeMs = 60 * 60_000;
5355
openLink.mockReset().mockResolvedValue(undefined);
5456
openChangeRequestLink.mockReset().mockReturnValue(false);
5557
showError.mockClear();
@@ -109,7 +111,8 @@ it("closes with the close button or Escape", async () => {
109111
});
110112

111113
async function renderInline() {
112-
await act(() =>
114+
// Async so a URL minted at mount lands inside act.
115+
await act(async () =>
113116
root.render(
114117
<HtmlRenderFrame
115118
environmentId={EnvironmentId.make("environment")}
@@ -123,7 +126,7 @@ async function renderInline() {
123126
);
124127
}
125128

126-
it("offers only full screen and opens with a fresh URL while keeping the inline page loaded", async () => {
129+
it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => {
127130
await renderInline();
128131
expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull();
129132
const inlineFrame = document.querySelector("iframe")!;
@@ -132,11 +135,10 @@ it("offers only full screen and opens with a fresh URL while keeping the inline
132135
'[aria-label="Open full screen"]',
133136
)!;
134137
expandButton.focus();
135-
refresh.mockResolvedValue("https://environment.test/renewed.html");
136138
await click("Open full screen");
137-
expect(refresh).toHaveBeenCalledOnce();
139+
expect(refresh).not.toHaveBeenCalled();
138140
expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
139-
"https://environment.test/renewed.html#",
141+
"https://environment.test/original.html#",
140142
);
141143
expect(inlineFrame.src).toBe(originalSrc);
142144
await click("Close");
@@ -145,9 +147,26 @@ it("offers only full screen and opens with a fresh URL while keeping the inline
145147
expect(document.activeElement).toBe(expandButton);
146148
});
147149

148-
it("routes links from the expanded page through its thread", async () => {
150+
// An inline URL near expiry is minted at mount, and full screen mints another.
151+
async function renderInlineNearExpiry() {
152+
cachedUrl.lifeMs = 60_000;
153+
refresh.mockResolvedValueOnce("https://environment.test/inline.html");
149154
await renderInline();
155+
expect(refresh).toHaveBeenCalledOnce();
156+
}
157+
158+
it("opens full screen with a fresh URL when the inline one is near expiry", async () => {
159+
await renderInlineNearExpiry();
150160
refresh.mockResolvedValue("https://environment.test/renewed.html");
161+
await click("Open full screen");
162+
expect(refresh).toHaveBeenCalledTimes(2);
163+
expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
164+
"https://environment.test/renewed.html#",
165+
);
166+
});
167+
168+
it("routes links from the expanded page through its thread", async () => {
169+
await renderInline();
151170
openChangeRequestLink.mockReturnValue(true);
152171
await click("Open full screen");
153172
const frame = document.querySelector<HTMLIFrameElement>('[role="dialog"] iframe')!;
@@ -173,7 +192,7 @@ it("routes links from the expanded page through its thread", async () => {
173192
it.each([null, new Error("Disconnected")])(
174193
"reports an unavailable URL instead of opening a blank page: %s",
175194
async (failure) => {
176-
await renderInline();
195+
await renderInlineNearExpiry();
177196
if (failure === null) refresh.mockResolvedValue(null);
178197
else refresh.mockRejectedValue(failure);
179198
await click("Open full screen");

‎apps/web/src/components/chat/HtmlRenderFrame.tsx‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ import {
66
type HtmlRenderReference,
77
} from "@t3tools/shared/htmlRender";
88
import { Maximize2Icon } from "lucide-react";
9-
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
9+
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
1010

1111
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
12+
import { cn } from "~/lib/utils";
1213

1314
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
1415
import { Button } from "../ui/button";
16+
import { Skeleton } from "../ui/skeleton";
1517
import { toastManager } from "../ui/toast";
1618
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
1719
import { HtmlRenderDialog } from "./HtmlRenderDialog";
@@ -64,7 +66,17 @@ export function HtmlRenderFrame(props: {
6466
// page again; one near expiry is minted afresh, since a frame cannot report a
6567
// failed load. The page keeps its first URL for its lifetime.
6668
const [src, setSrc] = useState<string | null>(null);
69+
// Full screen reuses the inline URL while it has life left, so the page
70+
// comes from the browser's cache instead of a new mint and download.
71+
const srcExpiresAt = useRef(0);
6772
const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
73+
// The page stays hidden behind a skeleton until it reports its content.
74+
const [ready, setReady] = useState(false);
75+
const showPage = useCallback(() => setReady(true), []);
76+
const fitPage = useCallback((contentHeight: number) => {
77+
setContentHeight(contentHeight);
78+
setReady(true);
79+
}, []);
6880
const { onFullscreenChange } = props;
6981
useEffect(() => {
7082
if (expandedSrc === null) return;
@@ -89,6 +101,7 @@ export function HtmlRenderFrame(props: {
89101
}
90102
if (cachedUrl === null) return;
91103
if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
104+
srcExpiresAt.current = cachedExpiresAt;
92105
setSrc(cachedUrl);
93106
return;
94107
}
@@ -101,14 +114,19 @@ export function HtmlRenderFrame(props: {
101114

102115
return (
103116
<div ref={boxRef} className="group/html-render relative" style={{ height }}>
117+
{!ready && !failed ? <HtmlRenderSkeleton title={title} height={height} /> : null}
104118
{src !== null ? (
105119
<>
106120
<HtmlRenderDocument
107121
src={src}
108122
title={title}
109123
threadRef={props.threadRef}
110-
className="block size-full"
111-
onContentHeight={setContentHeight}
124+
className={cn(
125+
"block size-full motion-safe:transition-opacity motion-safe:duration-200",
126+
!ready && "opacity-0",
127+
)}
128+
onContentHeight={fitPage}
129+
onLoad={showPage}
112130
/>
113131
<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">
114132
<Tooltip>
@@ -119,7 +137,10 @@ export function HtmlRenderFrame(props: {
119137
size="icon-xs"
120138
variant="glass"
121139
onClick={async () => {
122-
const url = await refresh().catch(() => null);
140+
const url =
141+
srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
142+
? src
143+
: await refresh().catch(() => null);
123144
if (url !== null) setExpandedSrc(url);
124145
else
125146
toastManager.add({
@@ -153,3 +174,26 @@ export function HtmlRenderFrame(props: {
153174
</div>
154175
);
155176
}
177+
178+
// One heading, a line of text, and a chart-sized block, the shape most pages
179+
// take, repeated to fill the frame's reserved height.
180+
const SKELETON_SECTION_HEIGHT = 264;
181+
182+
function HtmlRenderSkeleton(props: { readonly title: string; readonly height: number }) {
183+
const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT);
184+
return (
185+
<div
186+
role="status"
187+
aria-label={`Loading ${props.title}`}
188+
className="pointer-events-none absolute inset-0 flex flex-col gap-6 overflow-hidden pt-1"
189+
>
190+
{Array.from({ length: sections }, (_, index) => (
191+
<div key={index} className="flex shrink-0 flex-col gap-2">
192+
<Skeleton className="h-4 w-2/5" />
193+
<Skeleton className="h-3 w-3/5" />
194+
<Skeleton shape="card" className="mt-2 h-40 w-full" />
195+
</div>
196+
))}
197+
</div>
198+
);
199+
}

‎apps/web/src/components/files/BrowserDocumentFrame.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ export function HtmlRenderDocument(props: {
124124
readonly threadRef?: ScopedThreadRef | undefined;
125125
/** Receives the page's content height whenever it changes, so an inline frame can fit it. */
126126
readonly onContentHeight?: (height: number) => void;
127+
/** Called when the page has loaded. */
128+
readonly onLoad?: () => void;
127129
}) {
128130
const theme = useHtmlRenderTheme();
129131
const frameRef = useRef<HTMLIFrameElement>(null);
@@ -292,6 +294,7 @@ export function HtmlRenderDocument(props: {
292294
// Covers a theme change that landed while the page was loading.
293295
postTheme();
294296
postShortcuts();
297+
props.onLoad?.();
295298
}}
296299
// A frame whose color scheme differs from its document's paints an opaque
297300
// canvas, so the blank document a frame starts with would flash white in

0 commit comments

Comments
 (0)