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

htmlRender.ts

596 lines28.7 KB

1import {
2 T3_CODE_DARK_THEME_COLORS,
3 T3_CODE_LIGHT_THEME_COLORS,
4 type ThemeAppearance,
5 type ThemeColors,
6} from "./themePalettes.ts";
7import { EVENT_CODE_SHORTCUT_KEYS } from "./keybindings.ts";
8​
9/**
10 * Agent-authored HTML pages ("HTML renders") are self-contained documents an
11 * agent publishes into a thread with T3's `html_render` MCP tool. The server
12 * stores each one as a thread attachment with a small bootstrap injected into
13 * its head; clients show it in a sandboxed iframe (web, desktop) or WebView
14 * (mobile) and hand it the active theme as CSS custom properties.
15 */
16​
17export const HTML_RENDER_TOOL_NAME = "html_render";
18export const HTML_RENDER_MIN_HEIGHT = 80;
19export const HTML_RENDER_MAX_HEIGHT = 2000;
20export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
21​
22/** What the `html_render` tool result carries so clients can show the page. */
23export interface HtmlRenderReference {
24 readonly attachmentId: string;
25 readonly title: string;
26 /** The agent's frame height in CSS pixels, and the cap on any measured height. */
27 readonly height: number;
28 /**
29 * `[width, contentHeight]` pairs the server measured at publish, ascending by
30 * width. Absent when the preview browser was not installed yet.
31 */
32 readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
33 /**
34 * The page's main blocks at the column width, measured with `heights`, so a
35 * client can draw its loading skeleton in the page's shape. See
36 * `encodeHtmlRenderOutline`.
37 */
38 readonly outline?: string;
40​
41/** Frame widths the server measures a page at, from phones to the wide chat setting. */
42export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;
43​
44/**
45 * The reply column's frame width at the default chat width. Agents preview at
46 * it, and it picks the measured height when a client cannot know its width.
47 */
48export const HTML_RENDER_COLUMN_WIDTH = 728;
49​
50const MAX_MEASURED_HEIGHTS = 24;
51​
52function readMeasuredHeights(value: unknown) {
53 if (!Array.isArray(value) || value.length === 0 || value.length > MAX_MEASURED_HEIGHTS) {
54 return undefined;
55 }
56 const heights = value.flatMap((entry) =>
57 Array.isArray(entry) &&
58 entry.length === 2 &&
59 Number.isInteger(entry[0]) &&
60 entry[0] >= 1 &&
61 entry[0] <= 10_000 &&
62 typeof entry[1] === "number" &&
63 Number.isFinite(entry[1])
64 ? [[entry[0] as number, clampHtmlRenderHeight(entry[1])] as const]
65 : [],
66 );
67 return heights.length === value.length
68 ? [...heights].sort((left, right) => left[0] - right[0])
69 : undefined;
71​
72export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
73 if (typeof value !== "object" || value === null) return undefined;
74 const { attachmentId, title, height, heights, outline } = value as Record<string, unknown>;
75 if (
76 typeof attachmentId !== "string" ||
77 attachmentId.length === 0 ||
78 attachmentId.length > 256 ||
79 typeof title !== "string" ||
80 typeof height !== "number" ||
81 !Number.isFinite(height)
82 ) {
83 return undefined;
84 }
85 const measured = readMeasuredHeights(heights);
86 return {
87 attachmentId,
88 title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
89 height: clampHtmlRenderHeight(height),
90 ...(measured === undefined ? {} : { heights: measured }),
91 ...(measured !== undefined && typeof outline === "string" && OUTLINE_PATTERN.test(outline)
92 ? { outline }
93 : {}),
94 };
96​
97/** Whether two references show the same page at the same sizes. */
98export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: HtmlRenderReference) {
99 return (
100 left.attachmentId === right.attachmentId &&
101 left.title === right.title &&
102 left.height === right.height &&
103 left.outline === right.outline &&
104 (left.heights ?? []).length === (right.heights ?? []).length &&
105 (left.heights ?? []).every(
106 ([width, height], index) =>
107 right.heights?.[index]?.[0] === width && right.heights[index][1] === height,
108 )
109 );
111​
112// The taller of the heights measured at the nearest widths on each side. A
113// breakpoint between two measured widths can make the page as tall as either.
114function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
115 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
116 const high = above === -1 ? heights.length - 1 : above;
117 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
118 return Math.max(heights[low]![1], heights[high]![1]);
120​
121/**
122 * The frame height for a page at a frame width. It is the page's own reported
123 * `contentHeight` when the client has one, else the server's measurement for
124 * that width. A page even a few pixels taller than its frame scrolls inside it
125 * and takes the reader's scroll, so the frame fits the page. The agent's height
126 * caps it only when it is below the page's height at the column width (the
127 * agent asked for a scrolling frame) or when the page was never measured.
128 */
129export function htmlRenderFrameHeight(
130 reference: HtmlRenderReference,
131 width: number,
132 contentHeight?: number,
133) {
134 const heights = reference.heights;
135 if (heights === undefined || heights.length === 0) {
136 return clampHtmlRenderHeight(Math.min(reference.height, contentHeight ?? reference.height));
137 }
138 const cap =
139 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
140 ? reference.height
141 : HTML_RENDER_MAX_HEIGHT;
142 return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));
144​
145/**
146 * One block of a page's outline: `text` with its line count, a `media` element
147 * or solid shape, or a `table` with its row count.
148 */
149export interface HtmlRenderOutlineBox {
150 readonly kind: "text" | "media" | "table";
151 readonly x: number;
152 readonly y: number;
153 readonly width: number;
154 readonly height: number;
155 readonly lines: number;
157​
158const OUTLINE_KINDS = { t: "text", m: "media", g: "table" } as const;
159const OUTLINE_LETTERS = { text: "t", media: "m", table: "g" } as const;
160// Coordinates travel in 4px units, which keeps the tool result an agent reads short.
161const OUTLINE_UNIT = 4;
162export const HTML_RENDER_OUTLINE_MAX_BOXES = 48;
163// Sizes and line counts are never zero, so a client never divides by one.
164const OUTLINE_BOX = "[tmg]\\d{1,4},\\d{1,4},[1-9]\\d{0,3},[1-9]\\d{0,3},[1-9]\\d{0,2}";
165const OUTLINE_PATTERN = new RegExp(
166 `^${OUTLINE_BOX}(?:;${OUTLINE_BOX}){0,${HTML_RENDER_OUTLINE_MAX_BOXES - 1}}$`,
167);
168​
169/** Packs measured boxes, in CSS pixels at the column width, into an outline string. */
170export function encodeHtmlRenderOutline(
171 boxes: ReadonlyArray<HtmlRenderOutlineBox>,
172): string | undefined {
173 const unit = (value: number) => Math.min(9_999, Math.max(0, Math.round(value / OUTLINE_UNIT)));
174 const encoded = boxes
175 .slice(0, HTML_RENDER_OUTLINE_MAX_BOXES)
176 .flatMap((box) =>
177 unit(box.width) > 0 && unit(box.height) > 0
178 ? [
179 `${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)))}`,
180 ]
181 : [],
182 )
183 .join(";");
184 return encoded === "" ? undefined : encoded;
186​
187/**
188 * The outline's boxes in CSS pixels for a frame `width` wide, stretched to the
189 * page's measured height there. Empty without an outline.
190 */
191export function htmlRenderOutlineBoxes(
192 reference: HtmlRenderReference,
193 width: number,
194): ReadonlyArray<HtmlRenderOutlineBox> {
195 const heights = reference.heights;
196 if (reference.outline === undefined || heights === undefined || heights.length === 0) return [];
197 const scaleX = width / HTML_RENDER_COLUMN_WIDTH;
198 const scaleY = measuredHeight(heights, width) / measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH);
199 return reference.outline.split(";").map((entry) => {
200 const [x = 0, y = 0, boxWidth = 0, boxHeight = 0, lines = 1] = entry
201 .slice(1)
202 .split(",")
203 .map(Number);
204 return {
205 kind: OUTLINE_KINDS[entry[0] as keyof typeof OUTLINE_KINDS],
206 x: x * OUTLINE_UNIT * scaleX,
207 y: y * OUTLINE_UNIT * scaleY,
208 width: boxWidth * OUTLINE_UNIT * scaleX,
209 height: boxHeight * OUTLINE_UNIT * scaleY,
210 lines,
211 };
212 });
214​
215/** A readable download name: the title without characters file systems reject. */
216export function htmlRenderFileName(title: string) {
217 const name = title
218 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
219 .replace(/\s+/g, " ")
220 .trim()
221 .slice(0, 120)
222 .trim();
223 return `${name || "Page"}.html`;
225​
226export function clampHtmlRenderHeight(height: number): number {
227 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
229​
230export interface HtmlRenderFonts {
231 readonly sans: string;
232 readonly mono: string;
234​
235export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
236 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
237 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
238 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
239};
240​
241/**
242 * Fonts the server's headless browser lays pages out with. Arial-metric faces
243 * stand in for the system UI fonts readers see, so measured heights and
244 * preview screenshots wrap text close to how a client will.
245 */
246export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
247 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
248 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
249};
250​
251/** The resolved theme a client hands an HTML render. */
252export interface HtmlRenderTheme {
253 readonly appearance: ThemeAppearance;
254 readonly variables: Readonly<Record<string, string>>;
256​
257// Roles themes cannot change (index.css keeps info/success fixed), plus a
258// categorical chart series after the theme's own accent.
259const FIXED_COLORS = {
260 light: {
261 success: "#10b981",
262 successForeground: "#047857",
263 info: "#3b82f6",
264 infoForeground: "#1d4ed8",
265 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
266 },
267 dark: {
268 success: "#10b981",
269 successForeground: "#34d399",
270 info: "#3b82f6",
271 infoForeground: "#60a5fa",
272 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
273 },
274} as const;
275​
276/**
277 * Maps a theme palette to the variables HTML renders style against. Names
278 * follow the app's own tokens, except `--accent`, which is the theme's brand
279 * color here rather than the app's neutral hover surface.
280 */
281export function htmlRenderTheme(
282 colors: ThemeColors,
283 appearance: ThemeAppearance,
284 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
285): HtmlRenderTheme {
286 const fixed = FIXED_COLORS[appearance];
287 return {
288 appearance,
289 variables: {
290 "--background": colors.canvas,
291 "--foreground": colors.text,
292 "--muted": colors.muted,
293 "--muted-foreground": colors.mutedForeground,
294 "--card": colors.surface,
295 "--card-foreground": colors.text,
296 "--popover": colors.surfaceOverlay,
297 "--popover-foreground": colors.text,
298 "--secondary": colors.secondary,
299 "--secondary-foreground": colors.secondaryForeground,
300 "--border": colors.border,
301 "--input": colors.input,
302 "--ring": colors.focus,
303 "--primary": colors.messageAction,
304 "--primary-foreground": colors.messageActionForeground,
305 "--accent": colors.accent,
306 "--accent-foreground": colors.accentForeground,
307 "--accent-surface": colors.accentSurface,
308 "--accent-surface-foreground": colors.accentSurfaceForeground,
309 "--destructive": colors.error,
310 "--destructive-foreground": colors.errorForeground,
311 "--destructive-surface": colors.errorSurface,
312 "--warning": colors.warning,
313 "--warning-foreground": colors.warningForeground,
314 "--warning-surface": colors.warningSurface,
315 "--success": fixed.success,
316 "--success-foreground": fixed.successForeground,
317 "--info": fixed.info,
318 "--info-foreground": fixed.infoForeground,
319 "--code-background": colors.codeBackground,
320 "--code-foreground": colors.codeForeground,
321 "--chart-1": colors.accent,
322 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
323 "--radius": "0.625rem",
324 "--font-sans": fonts.sans,
325 "--font-mono": fonts.mono,
326 },
327 };
329​
330/** Agent-facing reference for the injected variables, used in tool descriptions. */
331export const HTML_RENDER_THEME_GUIDE = [
332 "T3 injects its active theme as CSS custom properties on :root, and they follow the user's theme and light/dark mode live:",
333 "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
334 "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
335 "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
336 "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
337 "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
338 "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
339 "The base stylesheet sets html background/color/font from these, body margin to 0, and hides the page's scrollbar; your own CSS overrides it.",
340].join(" ");
341​
342/** Agent-facing layout rules for a page that sits inside a reply. */
343export const HTML_RENDER_LAYOUT_GUIDE = [
344 `The frame is borderless on the thread's background, as wide as the reply column (${HTML_RENDER_COLUMN_WIDTH}px on desktop by default, wider if the reader widens chat, about 360px on phones), and its left edge lines up with your reply text.`,
345 "The page sits on the thread's own background, so by default leave html, body, and the outermost element with no background color. This overrides general style preferences such as a fixed black page background.",
346 "Use a fluid width with no horizontal padding on the outermost element, and no outer card, border, or banner title: the page is part of your reply.",
347 "If a box needs its own background (a mock of a specific screen, a panel that must stand apart), give it at least 16px of padding on every side and var(--radius) corners, so content never touches its edge.",
348 "Give charts fixed pixel heights rather than heights that scale with width.",
349 "Let content set the page's height. Avoid viewport-based heights such as 100vh or height:100% on html or body; the frame grows to fit the page, so they can make it grow again and again.",
350].join(" ");
351​
352// The bridge between a render and its client speaks the MCP Apps protocol
353// (JSON-RPC over postMessage), so the same host code can later drive upstream
354// MCP apps: https://github.com/modelcontextprotocol/ext-apps
355const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
356const OPEN_LINK_METHOD = "ui/open-link";
357const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
358// Not part of MCP Apps: a focused frame keeps its keys from the app, so the
359// client tells the page which chords are app shortcuts and the page passes
360// those on.
361const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
362const KEY_DOWN_METHOD = "t3/notifications/keydown";
363// Not part of MCP Apps: a click on a page image opens it in the app's image viewer.
364const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
365​
366/** The content height in a framed render's `ui/notifications/size-changed` notification. */
367export function readHtmlRenderContentHeight(data: unknown): number | undefined {
368 if (typeof data !== "object" || data === null) return undefined;
369 const { jsonrpc, method, params } = data as Record<string, unknown>;
370 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
371 const height =
372 typeof params === "object" && params !== null
373 ? (params as { height?: unknown }).height
374 : undefined;
375 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
377​
378/**
379 * A render's `ui/open-link` request, if `data` is one with an http(s) URL. The
380 * bootstrap adds the click's Cmd/Ctrl state, so a modifier click can leave the
381 * app the way it does from a chat link.
382 */
383export function readHtmlRenderLinkRequest(data: unknown):
384 | {
385 readonly id: string | number;
386 readonly url: string;
387 readonly metaKey: boolean;
388 readonly ctrlKey: boolean;
389 }
390 | undefined {
391 if (typeof data !== "object" || data === null) return undefined;
392 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
393 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
394 if (typeof id !== "string" && typeof id !== "number") return undefined;
395 if (typeof params !== "object" || params === null) return undefined;
396 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
397 return typeof url === "string" && /^https?:\/\//i.test(url)
398 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
399 : undefined;
401​
402/**
403 * The image a framed render's reader clicked, if `data` is an open-image
404 * notification for an http(s) or inline image URL. Server-side publishing
405 * inlines local images, so most arrive as `data:image/` URLs.
406 */
407export function readHtmlRenderImageRequest(
408 data: unknown,
409): { readonly src: string; readonly name: string } | undefined {
410 if (typeof data !== "object" || data === null) return undefined;
411 const { jsonrpc, method, params } = data as Record<string, unknown>;
412 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
413 if (typeof params !== "object" || params === null) return undefined;
414 const { src, name } = params as Record<string, unknown>;
415 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
416 const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";
417 return { src, name: label || "Image" };
419​
420/** The key a framed render passed on in a `t3/notifications/keydown` notification. */
421export function readHtmlRenderKeyDown(data: unknown):
422 | {
423 readonly key: string;
424 readonly code: string;
425 readonly metaKey: boolean;
426 readonly ctrlKey: boolean;
427 readonly shiftKey: boolean;
428 readonly altKey: boolean;
429 readonly repeat: boolean;
430 }
431 | undefined {
432 if (typeof data !== "object" || data === null) return undefined;
433 const { jsonrpc, method, params } = data as Record<string, unknown>;
434 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
435 if (typeof params !== "object" || params === null) return undefined;
436 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
437 string,
438 unknown
439 >;
440 if (typeof key !== "string" || typeof code !== "string") return undefined;
441 return {
442 key,
443 code,
444 metaKey: metaKey === true,
445 ctrlKey: ctrlKey === true,
446 shiftKey: shiftKey === true,
447 altKey: altKey === true,
448 repeat: repeat === true,
449 };
451​
452/** A chord as the page sees it: `mod` already resolved to Meta or Control. */
453export interface HtmlRenderShortcut {
454 /** Lowercase key name, as in a keybinding: `k`, `[`, `enter`. */
455 readonly key: string;
456 readonly metaKey: boolean;
457 readonly ctrlKey: boolean;
458 readonly shiftKey: boolean;
459 readonly altKey: boolean;
461​
462/**
463 * The `t3/notifications/shortcuts` notification a client posts into a render:
464 * the chords it may pass on, and chords of other commands that the page keeps
465 * even when one also matches an allowed chord.
466 */
467export function htmlRenderShortcutsMessage(
468 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
469 blocked: ReadonlyArray<HtmlRenderShortcut>,
470) {
471 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
473​
474/** The empty result a client sends back for a render's request. */
475export function htmlRenderResult(id: string | number) {
476 return { jsonrpc: "2.0", id, result: {} } as const;
478​
479const THEME_FRAGMENT_KEY = "t3-theme";
480​
481/** URL fragment that hands a render its theme before first paint. */
482export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
483 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
485​
486/** The `host-context-changed` notification a client posts into a mounted render when the theme changes. */
487export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
488 return {
489 jsonrpc: "2.0",
490 method: HOST_CONTEXT_CHANGED_METHOD,
491 params: { theme: theme.appearance, styles: { variables: theme.variables } },
492 } as const;
494​
495// The frame scrolls a page taller than itself, but a scrollbar inside the
496// reply reads as a box within the thread, so it stays hidden.
497const BASE_CSS =
498 "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;scrollbar-width:none}" +
499 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
500 // Focus outlines paint inside the element, so the frame edge never clips them.
501 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
502 // An image outside a link or button opens in the app's viewer, as chat images do.
503 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
504​
505function rootRule(theme: HtmlRenderTheme): string {
506 const declarations = Object.entries(theme.variables)
507 .map(([name, value]) => `${name}:${value};`)
508 .join("");
509 return `:root{color-scheme:${theme.appearance};${declarations}}`;
511​
512// Runs synchronously in <head>, before the page's own styles and body, so the
513// first paint is already themed. It rewrites its own <style> element rather
514// than setting inline properties, so a page's later `:root` rules still win,
515// then drops the fragment so a page's own hash routing never sees it. A link
516// the reader clicks to another page never replaces the page inside the thread:
517// a framed page asks its client to open it, and a top-level page (mobile)
518// opens it as a new window, which the client sends to the browser. A plain
519// left click on a framed page's image, outside a link or button and not
520// prevented by any of the page's listeners, asks the client to open the image
521// in its viewer. A framed page also reports its content height, measured as the server measures it,
522// so its client can fit the frame to the page. A chord the client named as an
523// app shortcut is passed on rather than left to the browser, unless a text
524// field has focus or the page handled it: the deciding listener is added while
525// the key dispatches, so it runs after every listener the page has. Keys
526// match as resolveEventKeys reads them, so the client accepts what it claims.
527const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href,metaKey:e.metaKey,ctrlKey:e.ctrlKey}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);window.addEventListener("click",function(e){var t=e.composedPath()[0],u;if(!e.isTrusted||e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||!t||t.tagName!=="IMG"||t.closest("a[href],button"))return;u=t.currentSrc||t.src;if(u)setTimeout(function(){if(!e.defaultPrevented)window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||""}},"*");});});var K=[],B=[],C=${JSON.stringify(EVENT_CODE_SHORTCUT_KEYS)};window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(e.source===window.parent&&d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(SHORTCUTS_METHOD)}&&p&&Array.isArray(p.shortcuts)&&Array.isArray(p.blocked)){K=p.shortcuts;B=p.blocked;}});window.addEventListener("keydown",function(e){var t=e.composedPath()[0],c=e.code||"",l=e.key.toLowerCase(),x=/^[a-z]$/.test(l)?[l]:[l,/^Key[A-Z]$/.test(c)?c.slice(3).toLowerCase():"",C.hasOwnProperty(c)?C[c]:""],f,m=function(s){return s&&s.metaKey===e.metaKey&&s.ctrlKey===e.ctrlKey&&s.shiftKey===e.shiftKey&&s.altKey===e.altKey&&x.indexOf(s.key)>-1;};if(!e.isTrusted||e.isComposing||e.getModifierState("AltGraph")&&!/^[a-z0-9]$/i.test(e.key)||t&&(t.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(t.tagName))||!K.some(m)||B.some(m))return;f=function(v){window.removeEventListener("keydown",f);if(v!==e||e.defaultPrevented)return;e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(KEY_DOWN_METHOD)},params:{key:e.key,code:e.code,metaKey:e.metaKey,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,repeat:e.repeat}},"*");};window.addEventListener("keydown",f);setTimeout(function(){window.removeEventListener("keydown",f);});},true);}})();`;
528​
529function bootstrapMarkup(markup: string): string {
530 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
531 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
532 // Without a client-provided theme (a direct download, the headless preview
533 // without a fragment) the page follows the OS appearance.
534 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
535 return [
536 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
537 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
538 ? ""
539 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
540 `<style id="t3-theme">${defaultCss}</style>`,
541 `<script>${BOOTSTRAP_SCRIPT}</script>`,
542 ].join("");
544​
545// Comments, raw text, and template contents are blanked to the same length,
546// so offsets still line up and inert tags cannot receive the bootstrap.
547const blankNonMarkup = (html: string) => {
548 const scan = html.replace(
549 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
550 (match) => " ".repeat(match.length),
551 );
552 const parts: string[] = [];
553 let depth = 0;
554 let start = 0;
555 let at = 0;
556 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
557 if (!match[1]) {
558 if (depth++ === 0) start = match.index;
559 } else if (depth > 0 && --depth === 0) {
560 const end = match.index + match[0].length;
561 parts.push(scan.slice(at, start), " ".repeat(end - start));
562 at = end;
563 }
564 }
565 if (depth > 0) {
566 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
567 at = scan.length;
568 }
569 parts.push(scan.slice(at));
570 return parts.join("");
571};
572​
573/**
574 * Inserts the theme bootstrap at the start of the document head, so a page's
575 * own styles and scripts come after it.
576 */
577export function injectHtmlRenderBootstrap(html: string): string {
578 const scan = blankNonMarkup(html);
579 const markup = bootstrapMarkup(scan);
580 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
581 if (headOpen) {
582 const at = headOpen.index + headOpen[0].length;
583 return html.slice(0, at) + markup + html.slice(at);
584 }
585 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
586 if (htmlOpen) {
587 const at = htmlOpen.index + htmlOpen[0].length;
588 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
589 }
590 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
591 if (doctype) {
592 const at = doctype[0].length;
593 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
594 }
595 return `<!doctype html><head>${markup}</head>${html}`;