TypeScript
perf(web): HTML renders drop the loading skeleton (#21480)
maria49b0f9683c27
diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.tsindex d3d953364b7..d4d3a0329d9 100644--- a/apps/server/src/htmlRender/HtmlRender.test.ts+++ b/apps/server/src/htmlRender/HtmlRender.test.ts@@ -446,7 +446,6 @@ describe("HtmlRender", () => {expect(reference.heights).toEqual(HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),);- expect(reference.outline).toBe("m0,0,182,91,1");}).pipe(Effect.provide(layerHtmlRender(executable)));}),30_000,diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.tsindex e927bd56a19..fdeebc6ae90 100644--- a/apps/server/src/htmlRender/HtmlRender.ts+++ b/apps/server/src/htmlRender/HtmlRender.ts@@ -345,7 +345,7 @@ const make = Effect.gen(function* () {Effect.gen(function* () {const executable = yield* previewBrowser.installed;if (Option.isNone(executable)) return undefined;- const { heights, outline } = yield* launching(executable.value, (noSandbox) =>+ const heights = yield* launching(executable.value, (noSandbox) =>HeadlessChrome.measureHtmlHeights({executable: executable.value,noSandbox,@@ -364,7 +364,7 @@ const make = Effect.gen(function* () {),}),);- return { heights: heights.toSorted(([left], [right]) => left - right), outline };+ return heights.toSorted(([left], [right]) => left - right);}).pipe(Effect.catch((cause) =>Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {@@ -405,7 +405,7 @@ const make = Effect.gen(function* () {if (attachmentId === null || filePath === null) {return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });}- const measured = yield* fileSystem.writeFileString(filePath, html).pipe(+ const heights = yield* fileSystem.writeFileString(filePath, html).pipe(Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),Effect.andThen(measure(html)),// Only the returned reference lets thread deletion find the page, so a@@ -416,8 +416,7 @@ const make = Effect.gen(function* () {attachmentId,title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",height: clampHtmlRenderHeight(input.height),- ...(measured === undefined ? {} : { heights: measured.heights }),- ...(measured?.outline === undefined ? {} : { outline: measured.outline }),+ ...(heights === undefined ? {} : { heights }),} satisfies HtmlRenderReference;});diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.tsindex 5c36cbb1d4d..7c476d392d3 100644--- a/apps/server/src/htmlRender/headlessChrome.ts+++ b/apps/server/src/htmlRender/headlessChrome.ts@@ -9,11 +9,6 @@ import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";-import {- encodeHtmlRenderOutline,- HTML_RENDER_COLUMN_WIDTH,- HTML_RENDER_OUTLINE_MAX_BOXES,-} from "@t3tools/shared/htmlRender";import { publicProxy } from "./publicProxy.ts";@@ -164,84 +159,6 @@ const SETTLE_EXPRESSION =const MEASURE_EXPRESSION ="(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";-const OUTLINE_MAX_VISITS = 2_000;-const OUTLINE_EXPRESSION = `(() => {- const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES};- const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button";- const pageBackground = getComputedStyle(document.documentElement).backgroundColor;- 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;- const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]);- const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20)));- // Text's own extent, so a short heading in a wide block stays short.- const addText = (el, s, r) => {- const range = document.createRange();- range.selectNodeContents(el);- const t = range.getBoundingClientRect();- const box = t.width >= 2 && t.height >= 2 ? t : r;- add("text", box, lineCount(s, box));- };- // Visits are capped too, so a huge generated DOM costs no more than a page.- let full = false, visits = 0;- // Whether an element holds text of its own, looking at its first few children only.- const hasOwnText = (el) => {- let n = el.firstChild;- for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true;- return false;- };- const walk = (parent, ps) => {- for (const el of parent.childNodes) {- // The last slot is kept for whatever the outline has no room left for.- if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; }- // Bare text only reaches here under body or a display: contents element.- if (el.nodeType === 3) {- if (el.data.trim() === "") continue;- const range = document.createRange();- range.selectNodeContents(el);- const t = range.getBoundingClientRect();- if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t));- continue;- }- if (el.nodeType !== 1) continue;- const s = getComputedStyle(el);- if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue;- if (s.display === "contents") { walk(el, s); continue; }- const r = el.getBoundingClientRect();- // A zero-size box can still show positioned children, unless it clips them.- if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; }- const tag = el.localName;- if (el.matches(media)) { add("media", r, 1); continue; }- if (tag === "table") { add("table", r, el.rows.length); continue; }- const text = hasOwnText(el);- if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; }- if (text) { addText(el, s, r); continue; }- if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; }- walk(el, s);- }- };- walk(document.body, getComputedStyle(document.body));- if (full) {- const top = Math.max(0, ...boxes.map((b) => b[2] + b[4]));- const root = document.documentElement;- const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top;- if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]);- }- return boxes;-})()`;-const Outlined = Schema.Struct({- result: Schema.Struct({- value: Schema.Array(- Schema.Tuple([- Schema.Literals(["text", "media", "table"]),- Schema.Finite,- Schema.Finite,- Schema.Finite,- Schema.Finite,- Schema.Finite,- ]),- ),- }),-});-const Ignored = Schema.Unknown;const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });@@ -601,27 +518,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: {Effect.ignore,);- const outline = send(- "Runtime.evaluate",- { expression: OUTLINE_EXPRESSION, returnByValue: true },- Outlined,- sessionId,- ).pipe(- Effect.map(({ result }) =>- encodeHtmlRenderOutline(- result.value.map(([kind, x, y, boxWidth, height, lines]) => ({- kind,- x,- y,- width: boxWidth,- height,- lines,- })),- ),- ),- );-- return { load, outline, screenshot, consoleMessages, close };+ return { load, screenshot, consoleMessages, close };});return { openPage };@@ -692,27 +589,15 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")profileDirectory: path.join(directory, "profile"),});const body = pageBody(input.html);- let outline: string | undefined;- const heights = yield* Effect.forEach(+ return yield* Effect.forEach(input.widths,(width) =>browser.openPage(width).pipe(Effect.flatMap((page) =>- page.load(body, input.urlFragment).pipe(- Effect.tap(() =>- width === HTML_RENDER_COLUMN_WIDTH- ? page.outline.pipe(- Effect.tap((value) => Effect.sync(() => (outline = value))),- Effect.ignore,- )- : Effect.void,- ),- Effect.ensuring(page.close),- ),+ page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),),Effect.map((height) => [width, height] as const),),{ concurrency: MEASURE_CONCURRENCY },);- return { heights, outline };}, Effect.scoped);diff --git a/apps/server/src/mcp/toolkits/html/tools.ts b/apps/server/src/mcp/toolkits/html/tools.tsindex 993acd9453e..4329ef5ab9e 100644--- a/apps/server/src/mcp/toolkits/html/tools.ts+++ b/apps/server/src/mcp/toolkits/html/tools.ts@@ -88,7 +88,6 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, {title: Schema.String,height: Schema.Number,heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))),- outline: Schema.optional(Schema.String),}),message: Schema.String,}),diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsxindex bd929a21b26..9989b5fe4a6 100644--- a/apps/web/src/components/chat/HtmlRenderFrame.tsx+++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx@@ -3,19 +3,15 @@ import {HTML_RENDER_COLUMN_WIDTH,htmlRenderFileName,htmlRenderFrameHeight,- htmlRenderOutlineBoxes,- type HtmlRenderOutlineBox,type HtmlRenderReference,} from "@t3tools/shared/htmlRender";import { Maximize2Icon } from "lucide-react";import { useEffect, useLayoutEffect, useRef, useState } from "react";import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";-import { cn } from "~/lib/utils";import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";import { Button } from "../ui/button";-import { Skeleton } from "../ui/skeleton";import { toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { HtmlRenderDialog } from "./HtmlRenderDialog";@@ -58,12 +54,6 @@ export function HtmlRenderFrame(props: {const [src, setSrc] = useState<string | null>(null);const srcExpiresAt = useRef(0);const [expandedSrc, setExpandedSrc] = useState<string | null>(null);- const [ready, setReady] = useState(false);- const showPage = () => setReady(true);- const fitPage = (contentHeight: number) => {- setContentHeight(contentHeight);- setReady(true);- };const { onFullscreenChange } = props;useEffect(() => {if (expandedSrc === null) return;@@ -101,25 +91,14 @@ export function HtmlRenderFrame(props: {return (<div ref={boxRef} className="group/html-render relative" style={{ height }}>- {!ready && !failed ? (- <HtmlRenderSkeleton- title={title}- height={height}- outline={htmlRenderOutlineBoxes(props.htmlRender, width)}- />- ) : null}{src !== null ? (<><HtmlRenderDocumentsrc={src}title={title}threadRef={props.threadRef}- className={cn(- "block size-full motion-safe:transition-opacity motion-safe:duration-200",- !ready && "opacity-0",- )}- onContentHeight={fitPage}- onLoad={showPage}+ className="block size-full"+ onContentHeight={setContentHeight}onFullscreenChange={onFullscreenChange}/><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: {</div>);}--const SKELETON_SECTION_HEIGHT = 264;--const OUTLINE_BOX_CLASS = {- media: "rounded-lg bg-muted-foreground/15",- text: "",- table: "",-} as const;--const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)";--function outlineBoxStyle(box: HtmlRenderOutlineBox): React.CSSProperties {- const style: React.CSSProperties = {- left: box.x,- top: box.y,- width: box.width,- height: box.height,- };- if (box.kind !== "text" && box.kind !== "table") return style;- const step = box.height / box.lines;- const bar = Math.min(box.kind === "table" ? 12 : 10, step * 0.6);- const start = (step - bar) / 2;- return {- ...style,- backgroundImage: `repeating-linear-gradient(to bottom, transparent 0 ${start}px, ${OUTLINE_BAR} ${start}px ${start + bar}px, transparent ${start + bar}px ${step}px)`,- };-}--function HtmlRenderSkeleton(props: {- readonly title: string;- readonly height: number;- readonly outline: ReadonlyArray<HtmlRenderOutlineBox>;-}) {- if (props.outline.length > 0) {- return (- <div- role="status"- aria-label={`Loading ${props.title}`}- className="pointer-events-none absolute inset-0 overflow-hidden motion-safe:animate-skeleton"- >- {props.outline.map((box) => (- <div- key={`${box.kind}:${box.x}:${box.y}:${box.width}:${box.height}`}- className={cn("absolute", OUTLINE_BOX_CLASS[box.kind])}- style={outlineBoxStyle(box)}- />- ))}- </div>- );- }- const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT);- return (- <div- role="status"- aria-label={`Loading ${props.title}`}- className="pointer-events-none absolute inset-0 flex flex-col gap-6 overflow-hidden pt-1"- >- {Array.from({ length: sections }, (_, index) => (- <div key={index} className="flex shrink-0 flex-col gap-2">- <Skeleton className="h-4 w-2/5" />- <Skeleton className="h-3 w-3/5" />- <Skeleton shape="card" className="mt-2 h-40 w-full" />- </div>- ))}- </div>- );-}diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsxindex e9f22abd699..8bd44e6e112 100644--- a/apps/web/src/components/files/BrowserDocumentFrame.tsx+++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx@@ -115,8 +115,6 @@ export function HtmlRenderDocument(props: {readonly onContentHeight?: (height: number) => void;/** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;- /** Called when the page has loaded. */- readonly onLoad?: () => void;}) {const theme = useHtmlRenderTheme();const frameRef = useRef<HTMLIFrameElement>(null);@@ -300,7 +298,6 @@ export function HtmlRenderDocument(props: {// Covers a theme change that landed while the page was loading.postTheme();postShortcuts();- props.onLoad?.();}}// A frame whose color scheme differs from its document's paints an opaque// canvas, so the blank document a frame starts with would flash white indiff --git a/packages/shared/src/htmlRender.test.ts b/packages/shared/src/htmlRender.test.tsindex 270fc50add6..fc45dc1f4b8 100644--- a/packages/shared/src/htmlRender.test.ts+++ b/packages/shared/src/htmlRender.test.ts@@ -1,10 +1,8 @@import { describe, expect, it } from "vite-plus/test";import {- encodeHtmlRenderOutline,HTML_RENDER_MAX_HEIGHT,htmlRenderFrameHeight,- htmlRenderOutlineBoxes,htmlRenderReferencesEqual,htmlRenderTheme,htmlRenderThemeFragment,@@ -290,48 +288,3 @@ describe("htmlRenderFrameHeight", () => {expect(htmlRenderReferencesEqual(measured, { ...copy, heights: [[390, 1290]] })).toBe(false);});});--describe("htmlRenderOutlineBoxes", () => {- const outline = encodeHtmlRenderOutline([- { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },- { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },- { kind: "media", x: 2, y: 2, width: 0, height: 10, lines: 1 },- ]);- const outlined = readHtmlRenderReference({- ...reference,- heights: [- [364, 1600],- [728, 800],- ],- outline,- })!;-- it("round-trips through a tool result and stretches to the client's width and height", () => {- expect(outline).toBe("t0,0,75,10,2;m0,12,182,75,1");- expect(htmlRenderOutlineBoxes(outlined, 728)).toEqual([- { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },- { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },- ]);- expect(htmlRenderOutlineBoxes(outlined, 364)[1]).toEqual({- kind: "media",- x: 0,- y: 96,- width: 364,- height: 600,- lines: 1,- });- });-- it("drops a malformed or unmeasured outline", () => {- expect(readHtmlRenderReference({ ...outlined, outline: "x1,2" })?.outline).toBeUndefined();- expect(- readHtmlRenderReference({ ...outlined, outline: "t0,0,10,10,0" })?.outline,- ).toBeUndefined();- expect(- readHtmlRenderReference({ ...outlined, outline: "m0,0,0,10,1" })?.outline,- ).toBeUndefined();- expect(readHtmlRenderReference({ ...reference, outline })?.outline).toBeUndefined();- expect(htmlRenderOutlineBoxes(reference, 728)).toEqual([]);- expect(htmlRenderReferencesEqual(outlined, { ...outlined, outline: "m0,0,1,1,1" })).toBe(false);- });-});diff --git a/packages/shared/src/htmlRender.ts b/packages/shared/src/htmlRender.tsindex 8d0dabefed3..b27bb09e97a 100644--- a/packages/shared/src/htmlRender.ts+++ b/packages/shared/src/htmlRender.ts@@ -16,7 +16,6 @@ export interface HtmlRenderReference {readonly title: string;readonly height: number;readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;- readonly outline?: string;}export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;@@ -47,7 +46,7 @@ function readMeasuredHeights(value: unknown) {export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {if (typeof value !== "object" || value === null) return undefined;- const { attachmentId, title, height, heights, outline } = value as Record<string, unknown>;+ const { attachmentId, title, height, heights } = value as Record<string, unknown>;if (typeof attachmentId !== "string" ||attachmentId.length === 0 ||@@ -64,9 +63,6 @@ export function readHtmlRenderReference(value: unknown): HtmlRenderReference | utitle: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",height: clampHtmlRenderHeight(height),...(measured === undefined ? {} : { heights: measured }),- ...(measured !== undefined && typeof outline === "string" && OUTLINE_PATTERN.test(outline)- ? { outline }- : {}),};}@@ -75,7 +71,6 @@ export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: Htmlleft.attachmentId === right.attachmentId &&left.title === right.title &&left.height === right.height &&- left.outline === right.outline &&(left.heights ?? []).length === (right.heights ?? []).length &&(left.heights ?? []).every(([width, height], index) =>@@ -113,65 +108,6 @@ export function htmlRenderFrameHeight(return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));}-export interface HtmlRenderOutlineBox {- readonly kind: "text" | "media" | "table";- readonly x: number;- readonly y: number;- readonly width: number;- readonly height: number;- readonly lines: number;-}--const OUTLINE_KINDS = { t: "text", m: "media", g: "table" } as const;-const OUTLINE_LETTERS = { text: "t", media: "m", table: "g" } as const;-const OUTLINE_UNIT = 4;-export const HTML_RENDER_OUTLINE_MAX_BOXES = 48;-const OUTLINE_BOX = "[tmg]\\d{1,4},\\d{1,4},[1-9]\\d{0,3},[1-9]\\d{0,3},[1-9]\\d{0,2}";-const OUTLINE_PATTERN = new RegExp(- `^${OUTLINE_BOX}(?:;${OUTLINE_BOX}){0,${HTML_RENDER_OUTLINE_MAX_BOXES - 1}}$`,-);--export function encodeHtmlRenderOutline(- boxes: ReadonlyArray<HtmlRenderOutlineBox>,-): string | undefined {- const unit = (value: number) => Math.min(9_999, Math.max(0, Math.round(value / OUTLINE_UNIT)));- const encoded = boxes- .slice(0, HTML_RENDER_OUTLINE_MAX_BOXES)- .flatMap((box) =>- unit(box.width) > 0 && unit(box.height) > 0- ? [- `${OUTLINE_LETTERS[box.kind]}${unit(box.x)},${unit(box.y)},${unit(box.width)},${unit(box.height)},${Math.min(999, Math.max(1, Math.round(box.lines)))}`,- ]- : [],- )- .join(";");- return encoded === "" ? undefined : encoded;-}--export function htmlRenderOutlineBoxes(- reference: HtmlRenderReference,- width: number,-): ReadonlyArray<HtmlRenderOutlineBox> {- const heights = reference.heights;- if (reference.outline === undefined || heights === undefined || heights.length === 0) return [];- const scaleX = width / HTML_RENDER_COLUMN_WIDTH;- const scaleY = measuredHeight(heights, width) / measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH);- return reference.outline.split(";").map((entry) => {- const [x = 0, y = 0, boxWidth = 0, boxHeight = 0, lines = 1] = entry- .slice(1)- .split(",")- .map(Number);- return {- kind: OUTLINE_KINDS[entry[0] as keyof typeof OUTLINE_KINDS],- x: x * OUTLINE_UNIT * scaleX,- y: y * OUTLINE_UNIT * scaleY,- width: boxWidth * OUTLINE_UNIT * scaleX,- height: boxHeight * OUTLINE_UNIT * scaleY,- lines,- };- });-}-export function htmlRenderFileName(title: string) {const name = title.replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")