Open History to see the last commit
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
9export const HTML_RENDER_TOOL_NAME = "html_render";
10export const HTML_RENDER_MIN_HEIGHT = 80;
11export const HTML_RENDER_MAX_HEIGHT = 2000;
12export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
13
14export interface HtmlRenderReference {
15 readonly attachmentId: string;
16 readonly title: string;
17 readonly height: number;
18 readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
19 readonly outline?: string;
20}
21
22export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;
23
24export const HTML_RENDER_COLUMN_WIDTH = 728;
25
26const MAX_MEASURED_HEIGHTS = 24;
27
28function readMeasuredHeights(value: unknown) {
29 if (!Array.isArray(value) || value.length === 0 || value.length > MAX_MEASURED_HEIGHTS) {
30 return undefined;
31 }
32 const heights = value.flatMap((entry) =>
33 Array.isArray(entry) &&
34 entry.length === 2 &&
35 Number.isInteger(entry[0]) &&
36 entry[0] >= 1 &&
37 entry[0] <= 10_000 &&
38 typeof entry[1] === "number" &&
39 Number.isFinite(entry[1])
40 ? [[entry[0] as number, clampHtmlRenderHeight(entry[1])] as const]
41 : [],
42 );
43 return heights.length === value.length
44 ? [...heights].sort((left, right) => left[0] - right[0])
45 : undefined;
46}
47
48export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
49 if (typeof value !== "object" || value === null) return undefined;
50 const { attachmentId, title, height, heights, outline } = value as Record<string, unknown>;
51 if (
52 typeof attachmentId !== "string" ||
53 attachmentId.length === 0 ||
54 attachmentId.length > 256 ||
55 typeof title !== "string" ||
56 typeof height !== "number" ||
57 !Number.isFinite(height)
58 ) {
59 return undefined;
60 }
61 const measured = readMeasuredHeights(heights);
62 return {
63 attachmentId,
64 title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
65 height: clampHtmlRenderHeight(height),
66 ...(measured === undefined ? {} : { heights: measured }),
67 ...(measured !== undefined && typeof outline === "string" && OUTLINE_PATTERN.test(outline)
68 ? { outline }
69 : {}),
70 };
71}
72
73export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: HtmlRenderReference) {
74 return (
75 left.attachmentId === right.attachmentId &&
76 left.title === right.title &&
77 left.height === right.height &&
78 left.outline === right.outline &&
79 (left.heights ?? []).length === (right.heights ?? []).length &&
80 (left.heights ?? []).every(
81 ([width, height], index) =>
82 right.heights?.[index]?.[0] === width && right.heights[index][1] === height,
83 )
84 );
85}
86
87// The taller of the heights measured at the nearest widths on each side. A
88// breakpoint between two measured widths can make the page as tall as either.
89function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
90 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
91 const high = above === -1 ? heights.length - 1 : above;
92 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
93 return Math.max(heights[low]![1], heights[high]![1]);
94}
95
96/**
97 * A page even a few pixels taller than its frame scrolls inside it and takes
98 * the reader's scroll, so the frame fits the page.
99 */
100export function htmlRenderFrameHeight(
101 reference: HtmlRenderReference,
102 width: number,
103 contentHeight?: number,
104) {
105 const heights = reference.heights;
106 if (heights === undefined || heights.length === 0) {
107 return clampHtmlRenderHeight(Math.min(reference.height, contentHeight ?? reference.height));
108 }
109 const cap =
110 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
111 ? reference.height
112 : HTML_RENDER_MAX_HEIGHT;
113 return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));
114}
115
116export interface HtmlRenderOutlineBox {
117 readonly kind: "text" | "media" | "table";
118 readonly x: number;
119 readonly y: number;
120 readonly width: number;
121 readonly height: number;
122 readonly lines: number;
123}
124
125const OUTLINE_KINDS = { t: "text", m: "media", g: "table" } as const;
126const OUTLINE_LETTERS = { text: "t", media: "m", table: "g" } as const;
127const OUTLINE_UNIT = 4;
128export const HTML_RENDER_OUTLINE_MAX_BOXES = 48;
129const OUTLINE_BOX = "[tmg]\\d{1,4},\\d{1,4},[1-9]\\d{0,3},[1-9]\\d{0,3},[1-9]\\d{0,2}";
130const OUTLINE_PATTERN = new RegExp(
131 `^${OUTLINE_BOX}(?:;${OUTLINE_BOX}){0,${HTML_RENDER_OUTLINE_MAX_BOXES - 1}}$`,
132);
133
134export function encodeHtmlRenderOutline(
135 boxes: ReadonlyArray<HtmlRenderOutlineBox>,
136): string | undefined {
137 const unit = (value: number) => Math.min(9_999, Math.max(0, Math.round(value / OUTLINE_UNIT)));
138 const encoded = boxes
139 .slice(0, HTML_RENDER_OUTLINE_MAX_BOXES)
140 .flatMap((box) =>
141 unit(box.width) > 0 && unit(box.height) > 0
142 ? [
143 `${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)))}`,
144 ]
145 : [],
146 )
147 .join(";");
148 return encoded === "" ? undefined : encoded;
149}
150
151export function htmlRenderOutlineBoxes(
152 reference: HtmlRenderReference,
153 width: number,
154): ReadonlyArray<HtmlRenderOutlineBox> {
155 const heights = reference.heights;
156 if (reference.outline === undefined || heights === undefined || heights.length === 0) return [];
157 const scaleX = width / HTML_RENDER_COLUMN_WIDTH;
158 const scaleY = measuredHeight(heights, width) / measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH);
159 return reference.outline.split(";").map((entry) => {
160 const [x = 0, y = 0, boxWidth = 0, boxHeight = 0, lines = 1] = entry
161 .slice(1)
162 .split(",")
163 .map(Number);
164 return {
165 kind: OUTLINE_KINDS[entry[0] as keyof typeof OUTLINE_KINDS],
166 x: x * OUTLINE_UNIT * scaleX,
167 y: y * OUTLINE_UNIT * scaleY,
168 width: boxWidth * OUTLINE_UNIT * scaleX,
169 height: boxHeight * OUTLINE_UNIT * scaleY,
170 lines,
171 };
172 });
173}
174
175export function htmlRenderFileName(title: string) {
176 const name = title
177 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
178 .replace(/\s+/g, " ")
179 .trim()
180 .slice(0, 120)
181 .trim();
182 return `${name || "Page"}.html`;
183}
184
185export function clampHtmlRenderHeight(height: number): number {
186 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
187}
188
189export interface HtmlRenderFonts {
190 readonly sans: string;
191 readonly mono: string;
192}
193
194export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
195 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
196 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
197 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
198};
199
200/**
201 * Arial-metric faces stand in for the system UI fonts readers see, so measured
202 * heights and preview screenshots wrap text close to how a client will.
203 */
204export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
205 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
206 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
207};
208
209export interface HtmlRenderTheme {
210 readonly appearance: ThemeAppearance;
211 readonly variables: Readonly<Record<string, string>>;
212}
213
214const FIXED_COLORS = {
215 light: {
216 success: "#10b981",
217 successForeground: "#047857",
218 info: "#3b82f6",
219 infoForeground: "#1d4ed8",
220 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
221 },
222 dark: {
223 success: "#10b981",
224 successForeground: "#34d399",
225 info: "#3b82f6",
226 infoForeground: "#60a5fa",
227 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
228 },
229} as const;
230
231/**
232 * Names follow the app's own tokens, except `--accent`, which is the theme's
233 * brand color here rather than the app's neutral hover surface.
234 */
235export function htmlRenderTheme(
236 colors: ThemeColors,
237 appearance: ThemeAppearance,
238 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
239): HtmlRenderTheme {
240 const fixed = FIXED_COLORS[appearance];
241 return {
242 appearance,
243 variables: {
244 "--background": colors.canvas,
245 "--foreground": colors.text,
246 "--muted": colors.muted,
247 "--muted-foreground": colors.mutedForeground,
248 "--card": colors.surface,
249 "--card-foreground": colors.text,
250 "--popover": colors.surfaceOverlay,
251 "--popover-foreground": colors.text,
252 "--secondary": colors.secondary,
253 "--secondary-foreground": colors.secondaryForeground,
254 "--border": colors.border,
255 "--input": colors.input,
256 "--ring": colors.focus,
257 "--primary": colors.messageAction,
258 "--primary-foreground": colors.messageActionForeground,
259 "--accent": colors.accent,
260 "--accent-foreground": colors.accentForeground,
261 "--accent-surface": colors.accentSurface,
262 "--accent-surface-foreground": colors.accentSurfaceForeground,
263 "--destructive": colors.error,
264 "--destructive-foreground": colors.errorForeground,
265 "--destructive-surface": colors.errorSurface,
266 "--warning": colors.warning,
267 "--warning-foreground": colors.warningForeground,
268 "--warning-surface": colors.warningSurface,
269 "--success": fixed.success,
270 "--success-foreground": fixed.successForeground,
271 "--info": fixed.info,
272 "--info-foreground": fixed.infoForeground,
273 "--code-background": colors.codeBackground,
274 "--code-foreground": colors.codeForeground,
275 "--chart-1": colors.accent,
276 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
277 "--radius": "0.625rem",
278 "--font-sans": fonts.sans,
279 "--font-mono": fonts.mono,
280 },
281 };
282}
283
284export const HTML_RENDER_THEME_GUIDE = [
285 "T3 injects its active theme as CSS custom properties on :root, and they follow the user's theme and light/dark mode live:",
286 "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
287 "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
288 "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
289 "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
290 "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
291 "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
292 "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.",
293].join(" ");
294
295export const HTML_RENDER_LAYOUT_GUIDE = [
296 `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.`,
297 "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.",
298 "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.",
299 "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.",
300 "Give charts fixed pixel heights rather than heights that scale with width.",
301 "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.",
302].join(" ");
303
304const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
305const OPEN_LINK_METHOD = "ui/open-link";
306const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
307// Not part of MCP Apps: a focused frame keeps its keys from the app, so the
308// client tells the page which chords are app shortcuts and the page passes
309// those on.
310const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
311const KEY_DOWN_METHOD = "t3/notifications/keydown";
312// Not part of MCP Apps: a click on a page image opens it in the app's image viewer.
313const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
314
315export function readHtmlRenderContentHeight(data: unknown): number | undefined {
316 if (typeof data !== "object" || data === null) return undefined;
317 const { jsonrpc, method, params } = data as Record<string, unknown>;
318 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
319 const height =
320 typeof params === "object" && params !== null
321 ? (params as { height?: unknown }).height
322 : undefined;
323 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
324}
325
326export function readHtmlRenderLinkRequest(data: unknown):
327 | {
328 readonly id: string | number;
329 readonly url: string;
330 readonly metaKey: boolean;
331 readonly ctrlKey: boolean;
332 }
333 | undefined {
334 if (typeof data !== "object" || data === null) return undefined;
335 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
336 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
337 if (typeof id !== "string" && typeof id !== "number") return undefined;
338 if (typeof params !== "object" || params === null) return undefined;
339 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
340 return typeof url === "string" && /^https?:\/\//i.test(url)
341 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
342 : undefined;
343}
344
345/**
346 * The image a framed render's reader clicked, if `data` is an open-image
347 * notification for an http(s) or inline image URL. Server-side publishing
348 * inlines local images, so most arrive as `data:image/` URLs.
349 */
350export function readHtmlRenderImageRequest(
351 data: unknown,
352): { readonly src: string; readonly name: string } | undefined {
353 if (typeof data !== "object" || data === null) return undefined;
354 const { jsonrpc, method, params } = data as Record<string, unknown>;
355 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
356 if (typeof params !== "object" || params === null) return undefined;
357 const { src, name } = params as Record<string, unknown>;
358 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
359 const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";
360 return { src, name: label || "Image" };
361}
362
363/** The key a framed render passed on in a `t3/notifications/keydown` notification. */
364export function readHtmlRenderKeyDown(data: unknown):
365 | {
366 readonly key: string;
367 readonly code: string;
368 readonly metaKey: boolean;
369 readonly ctrlKey: boolean;
370 readonly shiftKey: boolean;
371 readonly altKey: boolean;
372 readonly repeat: boolean;
373 }
374 | undefined {
375 if (typeof data !== "object" || data === null) return undefined;
376 const { jsonrpc, method, params } = data as Record<string, unknown>;
377 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
378 if (typeof params !== "object" || params === null) return undefined;
379 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
380 string,
381 unknown
382 >;
383 if (typeof key !== "string" || typeof code !== "string") return undefined;
384 return {
385 key,
386 code,
387 metaKey: metaKey === true,
388 ctrlKey: ctrlKey === true,
389 shiftKey: shiftKey === true,
390 altKey: altKey === true,
391 repeat: repeat === true,
392 };
393}
394
395export interface HtmlRenderShortcut {
396 readonly key: string;
397 readonly metaKey: boolean;
398 readonly ctrlKey: boolean;
399 readonly shiftKey: boolean;
400 readonly altKey: boolean;
401}
402
403export function htmlRenderShortcutsMessage(
404 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
405 blocked: ReadonlyArray<HtmlRenderShortcut>,
406) {
407 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
408}
409
410export function htmlRenderResult(id: string | number) {
411 return { jsonrpc: "2.0", id, result: {} } as const;
412}
413
414const THEME_FRAGMENT_KEY = "t3-theme";
415
416export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
417 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
418}
419
420export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
421 return {
422 jsonrpc: "2.0",
423 method: HOST_CONTEXT_CHANGED_METHOD,
424 params: { theme: theme.appearance, styles: { variables: theme.variables } },
425 } as const;
426}
427
428const BASE_CSS =
429 "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}" +
430 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
431 // Focus outlines paint inside the element, so the frame edge never clips them.
432 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
433 // An image outside a link or button opens in the app's viewer, as chat images do.
434 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
435
436function rootRule(theme: HtmlRenderTheme): string {
437 const declarations = Object.entries(theme.variables)
438 .map(([name, value]) => `${name}:${value};`)
439 .join("");
440 return `:root{color-scheme:${theme.appearance};${declarations}}`;
441}
442
443// Runs synchronously in <head>, before the page's own styles and body, so the
444// first paint is already themed. It rewrites its own <style> element rather
445// than setting inline properties, so a page's later `:root` rules still win,
446// then drops the fragment so a page's own hash routing never sees it. A link
447// the reader clicks to another page never replaces the page inside the thread:
448// a framed page asks its client to open it, and a top-level page (mobile)
449// opens it as a new window, which the client sends to the browser. A plain
450// left click on a framed page's image, outside a link or button and not
451// prevented by any of the page's listeners, asks the client to open the image
452// in its viewer. A framed page also reports its content height, measured as the server measures it,
453// so its client can fit the frame to the page. A chord the client named as an
454// app shortcut is passed on rather than left to the browser, unless a text
455// field has focus or the page handled it: the deciding listener is added while
456// the key dispatches, so it runs after every listener the page has. Keys
457// match as resolveEventKeys reads them, so the client accepts what it claims.
458const 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);}})();`;
459
460function bootstrapMarkup(markup: string): string {
461 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
462 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
463 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
464 return [
465 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
466 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
467 ? ""
468 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
469 `<style id="t3-theme">${defaultCss}</style>`,
470 `<script>${BOOTSTRAP_SCRIPT}</script>`,
471 ].join("");
472}
473
474// Comments, raw text, and template contents are blanked to the same length,
475// so offsets still line up and inert tags cannot receive the bootstrap.
476const blankNonMarkup = (html: string) => {
477 const scan = html.replace(
478 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
479 (match) => " ".repeat(match.length),
480 );
481 const parts: string[] = [];
482 let depth = 0;
483 let start = 0;
484 let at = 0;
485 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
486 if (!match[1]) {
487 if (depth++ === 0) start = match.index;
488 } else if (depth > 0 && --depth === 0) {
489 const end = match.index + match[0].length;
490 parts.push(scan.slice(at, start), " ".repeat(end - start));
491 at = end;
492 }
493 }
494 if (depth > 0) {
495 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
496 at = scan.length;
497 }
498 parts.push(scan.slice(at));
499 return parts.join("");
500};
501
502export function injectHtmlRenderBootstrap(html: string): string {
503 const scan = blankNonMarkup(html);
504 const markup = bootstrapMarkup(scan);
505 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
506 if (headOpen) {
507 const at = headOpen.index + headOpen[0].length;
508 return html.slice(0, at) + markup + html.slice(at);
509 }
510 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
511 if (htmlOpen) {
512 const at = htmlOpen.index + htmlOpen[0].length;
513 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
514 }
515 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
516 if (doctype) {
517 const at = doctype[0].length;
518 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
519 }
520 return `<!doctype html><head>${markup}</head>${html}`;
521}