Skip to content

Commit 49b0f96

Browse files
authored
perf(web): HTML renders drop the loading skeleton (#21480)
Co-authored-by: maria-rcks <[email protected]>
1 parent ab6be13 commit 49b0f96

8 files changed

Lines changed: 10 additions & 330 deletions

File tree

‎apps/server/src/htmlRender/HtmlRender.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,6 @@ describe("HtmlRender", () => {
446446
expect(reference.heights).toEqual(
447447
HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),
448448
);
449-
expect(reference.outline).toBe("m0,0,182,91,1");
450449
}).pipe(Effect.provide(layerHtmlRender(executable)));
451450
}),
452451
30_000,

‎apps/server/src/htmlRender/HtmlRender.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ const make = Effect.gen(function* () {
345345
Effect.gen(function* () {
346346
const executable = yield* previewBrowser.installed;
347347
if (Option.isNone(executable)) return undefined;
348-
const { heights, outline } = yield* launching(executable.value, (noSandbox) =>
348+
const heights = yield* launching(executable.value, (noSandbox) =>
349349
HeadlessChrome.measureHtmlHeights({
350350
executable: executable.value,
351351
noSandbox,
@@ -364,7 +364,7 @@ const make = Effect.gen(function* () {
364364
),
365365
}),
366366
);
367-
return { heights: heights.toSorted(([left], [right]) => left - right), outline };
367+
return heights.toSorted(([left], [right]) => left - right);
368368
}).pipe(
369369
Effect.catch((cause) =>
370370
Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
@@ -405,7 +405,7 @@ const make = Effect.gen(function* () {
405405
if (attachmentId === null || filePath === null) {
406406
return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
407407
}
408-
const measured = yield* fileSystem.writeFileString(filePath, html).pipe(
408+
const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
409409
Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
410410
Effect.andThen(measure(html)),
411411
// Only the returned reference lets thread deletion find the page, so a
@@ -416,8 +416,7 @@ const make = Effect.gen(function* () {
416416
attachmentId,
417417
title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
418418
height: clampHtmlRenderHeight(input.height),
419-
...(measured === undefined ? {} : { heights: measured.heights }),
420-
...(measured?.outline === undefined ? {} : { outline: measured.outline }),
419+
...(heights === undefined ? {} : { heights }),
421420
} satisfies HtmlRenderReference;
422421
});
423422

‎apps/server/src/htmlRender/headlessChrome.ts‎

Lines changed: 3 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,6 @@ import * as Schema from "effect/Schema";
99
import * as Stream from "effect/Stream";
1010
import * as ChildProcess from "effect/process/ChildProcess";
1111
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12-
import {
13-
encodeHtmlRenderOutline,
14-
HTML_RENDER_COLUMN_WIDTH,
15-
HTML_RENDER_OUTLINE_MAX_BOXES,
16-
} from "@t3tools/shared/htmlRender";
1712

1813
import { publicProxy } from "./publicProxy.ts";
1914

@@ -164,84 +159,6 @@ const SETTLE_EXPRESSION =
164159
const MEASURE_EXPRESSION =
165160
"(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
166161

167-
const OUTLINE_MAX_VISITS = 2_000;
168-
const OUTLINE_EXPRESSION = `(() => {
169-
const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES};
170-
const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button";
171-
const pageBackground = getComputedStyle(document.documentElement).backgroundColor;
172-
const filled = (s) => (s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== pageBackground) || s.backgroundImage !== "none" || parseFloat(s.borderTopWidth) + parseFloat(s.borderBottomWidth) + parseFloat(s.borderLeftWidth) > 0;
173-
const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]);
174-
const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20)));
175-
// Text's own extent, so a short heading in a wide block stays short.
176-
const addText = (el, s, r) => {
177-
const range = document.createRange();
178-
range.selectNodeContents(el);
179-
const t = range.getBoundingClientRect();
180-
const box = t.width >= 2 && t.height >= 2 ? t : r;
181-
add("text", box, lineCount(s, box));
182-
};
183-
// Visits are capped too, so a huge generated DOM costs no more than a page.
184-
let full = false, visits = 0;
185-
// Whether an element holds text of its own, looking at its first few children only.
186-
const hasOwnText = (el) => {
187-
let n = el.firstChild;
188-
for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true;
189-
return false;
190-
};
191-
const walk = (parent, ps) => {
192-
for (const el of parent.childNodes) {
193-
// The last slot is kept for whatever the outline has no room left for.
194-
if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; }
195-
// Bare text only reaches here under body or a display: contents element.
196-
if (el.nodeType === 3) {
197-
if (el.data.trim() === "") continue;
198-
const range = document.createRange();
199-
range.selectNodeContents(el);
200-
const t = range.getBoundingClientRect();
201-
if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t));
202-
continue;
203-
}
204-
if (el.nodeType !== 1) continue;
205-
const s = getComputedStyle(el);
206-
if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue;
207-
if (s.display === "contents") { walk(el, s); continue; }
208-
const r = el.getBoundingClientRect();
209-
// A zero-size box can still show positioned children, unless it clips them.
210-
if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; }
211-
const tag = el.localName;
212-
if (el.matches(media)) { add("media", r, 1); continue; }
213-
if (tag === "table") { add("table", r, el.rows.length); continue; }
214-
const text = hasOwnText(el);
215-
if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; }
216-
if (text) { addText(el, s, r); continue; }
217-
if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; }
218-
walk(el, s);
219-
}
220-
};
221-
walk(document.body, getComputedStyle(document.body));
222-
if (full) {
223-
const top = Math.max(0, ...boxes.map((b) => b[2] + b[4]));
224-
const root = document.documentElement;
225-
const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top;
226-
if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]);
227-
}
228-
return boxes;
229-
})()`;
230-
const Outlined = Schema.Struct({
231-
result: Schema.Struct({
232-
value: Schema.Array(
233-
Schema.Tuple([
234-
Schema.Literals(["text", "media", "table"]),
235-
Schema.Finite,
236-
Schema.Finite,
237-
Schema.Finite,
238-
Schema.Finite,
239-
Schema.Finite,
240-
]),
241-
),
242-
}),
243-
});
244-
245162
const Ignored = Schema.Unknown;
246163
const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
247164
const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
@@ -601,27 +518,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
601518
Effect.ignore,
602519
);
603520

604-
const outline = send(
605-
"Runtime.evaluate",
606-
{ expression: OUTLINE_EXPRESSION, returnByValue: true },
607-
Outlined,
608-
sessionId,
609-
).pipe(
610-
Effect.map(({ result }) =>
611-
encodeHtmlRenderOutline(
612-
result.value.map(([kind, x, y, boxWidth, height, lines]) => ({
613-
kind,
614-
x,
615-
y,
616-
width: boxWidth,
617-
height,
618-
lines,
619-
})),
620-
),
621-
),
622-
);
623-
624-
return { load, outline, screenshot, consoleMessages, close };
521+
return { load, screenshot, consoleMessages, close };
625522
});
626523

627524
return { openPage };
@@ -692,27 +589,15 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")
692589
profileDirectory: path.join(directory, "profile"),
693590
});
694591
const body = pageBody(input.html);
695-
let outline: string | undefined;
696-
const heights = yield* Effect.forEach(
592+
return yield* Effect.forEach(
697593
input.widths,
698594
(width) =>
699595
browser.openPage(width).pipe(
700596
Effect.flatMap((page) =>
701-
page.load(body, input.urlFragment).pipe(
702-
Effect.tap(() =>
703-
width === HTML_RENDER_COLUMN_WIDTH
704-
? page.outline.pipe(
705-
Effect.tap((value) => Effect.sync(() => (outline = value))),
706-
Effect.ignore,
707-
)
708-
: Effect.void,
709-
),
710-
Effect.ensuring(page.close),
711-
),
597+
page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
712598
),
713599
Effect.map((height) => [width, height] as const),
714600
),
715601
{ concurrency: MEASURE_CONCURRENCY },
716602
);
717-
return { heights, outline };
718603
}, Effect.scoped);

‎apps/server/src/mcp/toolkits/html/tools.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,6 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, {
8888
title: Schema.String,
8989
height: Schema.Number,
9090
heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))),
91-
outline: Schema.optional(Schema.String),
9291
}),
9392
message: Schema.String,
9493
}),

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

Lines changed: 2 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,15 @@ import {
33
HTML_RENDER_COLUMN_WIDTH,
44
htmlRenderFileName,
55
htmlRenderFrameHeight,
6-
htmlRenderOutlineBoxes,
7-
type HtmlRenderOutlineBox,
86
type HtmlRenderReference,
97
} from "@t3tools/shared/htmlRender";
108
import { Maximize2Icon } from "lucide-react";
119
import { useEffect, useLayoutEffect, useRef, useState } from "react";
1210

1311
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
14-
import { cn } from "~/lib/utils";
1512

1613
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
1714
import { Button } from "../ui/button";
18-
import { Skeleton } from "../ui/skeleton";
1915
import { toastManager } from "../ui/toast";
2016
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
2117
import { HtmlRenderDialog } from "./HtmlRenderDialog";
@@ -58,12 +54,6 @@ export function HtmlRenderFrame(props: {
5854
const [src, setSrc] = useState<string | null>(null);
5955
const srcExpiresAt = useRef(0);
6056
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-
};
6757
const { onFullscreenChange } = props;
6858
useEffect(() => {
6959
if (expandedSrc === null) return;
@@ -101,25 +91,14 @@ export function HtmlRenderFrame(props: {
10191

10292
return (
10393
<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}
11194
{src !== null ? (
11295
<>
11396
<HtmlRenderDocument
11497
src={src}
11598
title={title}
11699
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}
100+
className="block size-full"
101+
onContentHeight={setContentHeight}
123102
onFullscreenChange={onFullscreenChange}
124103
/>
125104
<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">
@@ -168,70 +147,3 @@ export function HtmlRenderFrame(props: {
168147
</div>
169148
);
170149
}
171-
172-
const SKELETON_SECTION_HEIGHT = 264;
173-
174-
const OUTLINE_BOX_CLASS = {
175-
media: "rounded-lg bg-muted-foreground/15",
176-
text: "",
177-
table: "",
178-
} as const;
179-
180-
const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)";
181-
182-
function 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-
};
197-
}
198-
199-
function 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-
);
237-
}

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

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,6 @@ export function HtmlRenderDocument(props: {
115115
readonly onContentHeight?: (height: number) => void;
116116
/** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */
117117
readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
118-
/** Called when the page has loaded. */
119-
readonly onLoad?: () => void;
120118
}) {
121119
const theme = useHtmlRenderTheme();
122120
const frameRef = useRef<HTMLIFrameElement>(null);
@@ -300,7 +298,6 @@ export function HtmlRenderDocument(props: {
300298
// Covers a theme change that landed while the page was loading.
301299
postTheme();
302300
postShortcuts();
303-
props.onLoad?.();
304301
}}
305302
// A frame whose color scheme differs from its document's paints an opaque
306303
// canvas, so the blank document a frame starts with would flash white in

0 commit comments

Comments
 (0)