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;
12// A client fits the frame to the live page up to this height. It only stops a
13// page that grows with its frame, since vh units are rejected at publish.
14export const HTML_RENDER_MAX_FIT_HEIGHT = 20_000;
15export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
16
17export interface HtmlRenderReference {
18 readonly attachmentId: string;
19 readonly title: string;
20 readonly height: number;
21 readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
22}
23
24export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;
25
26export const HTML_RENDER_COLUMN_WIDTH = 728;
27
28const MAX_MEASURED_HEIGHTS = 24;
29
30function readMeasuredHeights(value: unknown) {
31 if (!Array.isArray(value) || value.length === 0 || value.length > MAX_MEASURED_HEIGHTS) {
32 return undefined;
33 }
34 const heights = value.flatMap((entry) =>
35 Array.isArray(entry) &&
36 entry.length === 2 &&
37 Number.isInteger(entry[0]) &&
38 entry[0] >= 1 &&
39 entry[0] <= 10_000 &&
40 typeof entry[1] === "number" &&
41 Number.isFinite(entry[1])
42 ? [[entry[0] as number, clampHtmlRenderHeight(entry[1])] as const]
43 : [],
44 );
45 return heights.length === value.length
46 ? [...heights].sort((left, right) => left[0] - right[0])
47 : undefined;
48}
49
50export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
51 if (typeof value !== "object" || value === null) return undefined;
52 const { attachmentId, title, height, heights } = value as Record<string, unknown>;
53 if (
54 typeof attachmentId !== "string" ||
55 attachmentId.length === 0 ||
56 attachmentId.length > 256 ||
57 typeof title !== "string" ||
58 typeof height !== "number" ||
59 !Number.isFinite(height)
60 ) {
61 return undefined;
62 }
63 const measured = readMeasuredHeights(heights);
64 return {
65 attachmentId,
66 title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
67 height: clampHtmlRenderHeight(height),
68 ...(measured === undefined ? {} : { heights: measured }),
69 };
70}
71
72export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: HtmlRenderReference) {
73 return (
74 left.attachmentId === right.attachmentId &&
75 left.title === right.title &&
76 left.height === right.height &&
77 (left.heights ?? []).length === (right.heights ?? []).length &&
78 (left.heights ?? []).every(
79 ([width, height], index) =>
80 right.heights?.[index]?.[0] === width && right.heights[index][1] === height,
81 )
82 );
83}
84
85// Use the taller neighboring measurement because breakpoints can select either height.
86function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
87 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
88 if (above === -1) return heights[heights.length - 1]![1];
89 const low = heights[above]![0] === width ? above : Math.max(0, above - 1);
90 return Math.max(heights[low]![1], heights[above]![1]);
91}
92
93/**
94 * A page even a few pixels taller than its frame scrolls inside it and takes
95 * the reader's scroll, so the frame fits the page. A client that measured the
96 * live page passes `contentHeight`, which wins over the agent's height: client
97 * fonts often wrap the page taller than the server or agent measured it.
98 */
99export function htmlRenderFrameHeight(
100 reference: HtmlRenderReference,
101 width: number,
102 contentHeight?: number,
103) {
104 if (contentHeight !== undefined) {
105 return Math.min(
106 HTML_RENDER_MAX_FIT_HEIGHT,
107 Math.max(HTML_RENDER_MIN_HEIGHT, Math.ceil(contentHeight)),
108 );
109 }
110 const heights = reference.heights;
111 if (heights === undefined || heights.length === 0) {
112 return clampHtmlRenderHeight(reference.height);
113 }
114 const cap =
115 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
116 ? reference.height
117 : HTML_RENDER_MAX_HEIGHT;
118 return clampHtmlRenderHeight(Math.min(cap, measuredHeight(heights, width)));
119}
120
121export function htmlRenderFileName(title: string) {
122 const name = title
123 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
124 .replace(/\s+/g, " ")
125 .trim()
126 .slice(0, 120)
127 .replace(/\p{Surrogate}$/u, "")
128 .trim();
129 return `${name || "Page"}.html`;
130}
131
132export function clampHtmlRenderHeight(height: number): number {
133 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
134}
135
136export interface HtmlRenderFonts {
137 readonly sans: string;
138 readonly mono: string;
139}
140
141export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
142 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
143 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
144 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
145};
146
147/** Arial-metric substitutes keep measured wrapping close to client system fonts. */
148export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
149 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
150 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
151};
152
153export interface HtmlRenderTheme {
154 readonly appearance: ThemeAppearance;
155 readonly variables: Readonly<Record<string, string>>;
156}
157
158const FIXED_COLORS = {
159 light: {
160 success: "#10b981",
161 successForeground: "#047857",
162 info: "#3b82f6",
163 infoForeground: "#1d4ed8",
164 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
165 },
166 dark: {
167 success: "#10b981",
168 successForeground: "#34d399",
169 info: "#3b82f6",
170 infoForeground: "#60a5fa",
171 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
172 },
173} as const;
174
175type Rgb = readonly [number, number, number];
176
177function parseHexColor(color: string): Rgb | undefined {
178 if (!/^#[0-9a-f]{6}$/iu.test(color)) return undefined;
179 const channel = (offset: number) => Number.parseInt(color.slice(offset, offset + 2), 16);
180 return [channel(1), channel(3), channel(5)];
181}
182
183function luminance(rgb: Rgb): number {
184 const [r, g, b] = rgb.map((value) => {
185 const scaled = value / 255;
186 return scaled <= 0.04045 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
187 });
188 return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;
189}
190
191function contrastRatio(a: Rgb, b: Rgb): number {
192 const [first, second] = [luminance(a), luminance(b)];
193 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
194}
195
196/** Moves `color` toward white or black until lines drawn with it reach WCAG's 3:1 on `background`. */
197function graphicColorOn(color: string, background: string): string {
198 const ink = parseHexColor(color);
199 const paper = parseHexColor(background);
200 if (ink === undefined || paper === undefined || contrastRatio(ink, paper) >= 3) return color;
201 const target = contrastRatio([255, 255, 255], paper) >= contrastRatio([0, 0, 0], paper) ? 255 : 0;
202 let mixed = ink;
203 for (let step = 1; step <= 20 && contrastRatio(mixed, paper) < 3; step += 1) {
204 const toward = (value: number) => Math.round(value + ((target - value) * step) / 20);
205 mixed = [toward(ink[0]), toward(ink[1]), toward(ink[2])];
206 }
207 return `#${mixed.map((value) => value.toString(16).padStart(2, "0")).join("")}`;
208}
209
210/** Uses app tokens, except --accent is the brand color rather than a neutral hover surface. */
211export function htmlRenderTheme(
212 colors: ThemeColors,
213 appearance: ThemeAppearance,
214 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
215): HtmlRenderTheme {
216 const fixed = FIXED_COLORS[appearance];
217 const accent = graphicColorOn(colors.accent, colors.canvas);
218 return {
219 appearance,
220 variables: {
221 "--background": colors.canvas,
222 "--foreground": colors.text,
223 "--muted": colors.muted,
224 "--muted-foreground": colors.mutedForeground,
225 "--card": colors.surface,
226 "--card-foreground": colors.text,
227 "--popover": colors.surfaceOverlay,
228 "--popover-foreground": colors.text,
229 "--secondary": colors.secondary,
230 "--secondary-foreground": colors.secondaryForeground,
231 "--border": colors.border,
232 "--input": colors.input,
233 "--ring": colors.focus,
234 "--primary": colors.messageAction,
235 "--primary-foreground": colors.messageActionForeground,
236 "--accent": accent,
237 "--accent-foreground": colors.accentForeground,
238 "--accent-surface": colors.accentSurface,
239 "--accent-surface-foreground": colors.accentSurfaceForeground,
240 "--destructive": colors.error,
241 "--destructive-foreground": colors.errorForeground,
242 "--destructive-surface": colors.errorSurface,
243 "--warning": colors.warning,
244 "--warning-foreground": colors.warningForeground,
245 "--warning-surface": colors.warningSurface,
246 "--success": fixed.success,
247 "--success-foreground": fixed.successForeground,
248 "--info": fixed.info,
249 "--info-foreground": fixed.infoForeground,
250 "--code-background": colors.codeBackground,
251 "--code-foreground": colors.codeForeground,
252 "--chart-1": accent,
253 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
254 "--radius": "0.625rem",
255 "--font-sans": fonts.sans,
256 "--font-mono": fonts.mono,
257 },
258 };
259}
260
261export const HTML_RENDER_THEME_GUIDE = [
262 "Use theme CSS variables on :root, not fixed colors:",
263 "--background, --foreground, --muted, --card, --popover, --secondary, --border, --ring, --primary, --accent, --destructive, --warning, --success, --info, --code-background",
264 "(most have a matching -foreground; accent, destructive, and warning also have -surface),",
265 "--chart-1 to --chart-6, --radius, --font-sans, --font-mono.",
266 "The base sheet sets background, text, and font.",
267].join(" ");
268
269export const HTML_RENDER_LAYOUT_GUIDE = [
270 `Frame width is reply width (${HTML_RENDER_COLUMN_WIDTH}px desktop, about 360px phones), on the thread background.`,
271 "Leave html, body, and the outer element with no background color, no outer card, border, banner title, or side padding. This wins over any rule that sets a page background.",
272 "T3 adds an overridable 8px html gutter for selection rings and shadows. Use fluid widths within it.",
273 "A box that needs its own background gets 16px padding and var(--radius) corners. Give charts fixed pixel heights.",
274 "Let content set the height. Do not use vh units or height:100% on html or body. Both are rejected or loop.",
275].join(" ");
276
277const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
278const OPEN_LINK_METHOD = "ui/open-link";
279const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
280// Custom bridge forwards app shortcuts because focused frames otherwise capture them.
281const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
282const KEY_DOWN_METHOD = "t3/notifications/keydown";
283const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
284
285export function readHtmlRenderContentHeight(data: unknown): number | undefined {
286 if (typeof data !== "object" || data === null) return undefined;
287 const { jsonrpc, method, params } = data as Record<string, unknown>;
288 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
289 const height =
290 typeof params === "object" && params !== null
291 ? (params as { height?: unknown }).height
292 : undefined;
293 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
294}
295
296export function readHtmlRenderLinkRequest(data: unknown):
297 | {
298 readonly id: string | number;
299 readonly url: string;
300 readonly metaKey: boolean;
301 readonly ctrlKey: boolean;
302 }
303 | undefined {
304 if (typeof data !== "object" || data === null) return undefined;
305 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
306 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
307 if (typeof id !== "string" && typeof id !== "number") return undefined;
308 if (typeof params !== "object" || params === null) return undefined;
309 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
310 return typeof url === "string" && /^https?:\/\//i.test(url)
311 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
312 : undefined;
313}
314
315interface HtmlRenderImage {
316 readonly src: string;
317 readonly name: string;
318}
319
320function readHtmlRenderImage(src: unknown, name: unknown): HtmlRenderImage | undefined {
321 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
322 const trimmed = typeof name === "string" ? name.trim() : "";
323 // The page sends any alt text; never end the label on half an emoji.
324 const last = trimmed.charCodeAt(HTML_RENDER_MAX_TITLE_LENGTH - 1);
325 const end = HTML_RENDER_MAX_TITLE_LENGTH - (last >= 0xd800 && last <= 0xdbff ? 1 : 0);
326 const label = trimmed.slice(0, end);
327 return { src, name: label || "Image" };
328}
329
330/**
331 * Published local images arrive as `data:image/` URLs. `images` and `index` carry the
332 * page's other images; a page bootstrapped by an older server sends only `src` and `name`.
333 */
334export function readHtmlRenderImageRequest(
335 data: unknown,
336): { readonly images: ReadonlyArray<HtmlRenderImage>; readonly index: number } | undefined {
337 if (typeof data !== "object" || data === null) return undefined;
338 const { jsonrpc, method, params } = data as Record<string, unknown>;
339 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
340 if (typeof params !== "object" || params === null) return undefined;
341 const { src, name, images, index } = params as Record<string, unknown>;
342 const clicked = readHtmlRenderImage(src, name);
343 if (clicked === undefined) return undefined;
344 const gallery: HtmlRenderImage[] = [];
345 let at = -1;
346 if (Array.isArray(images)) {
347 images.forEach((entry: unknown, position) => {
348 if (typeof entry !== "object" || entry === null) return;
349 const image = readHtmlRenderImage(
350 (entry as Record<string, unknown>).src,
351 (entry as Record<string, unknown>).name,
352 );
353 if (image === undefined) return;
354 if (position === index) at = gallery.length;
355 gallery.push(image);
356 });
357 }
358 return at >= 0 && gallery[at]?.src === clicked.src
359 ? { images: gallery, index: at }
360 : { images: [clicked], index: 0 };
361}
362
363export function readHtmlRenderKeyDown(data: unknown):
364 | {
365 readonly key: string;
366 readonly code: string;
367 readonly metaKey: boolean;
368 readonly ctrlKey: boolean;
369 readonly shiftKey: boolean;
370 readonly altKey: boolean;
371 readonly repeat: boolean;
372 }
373 | undefined {
374 if (typeof data !== "object" || data === null) return undefined;
375 const { jsonrpc, method, params } = data as Record<string, unknown>;
376 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
377 if (typeof params !== "object" || params === null) return undefined;
378 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
379 string,
380 unknown
381 >;
382 if (typeof key !== "string" || typeof code !== "string") return undefined;
383 return {
384 key,
385 code,
386 metaKey: metaKey === true,
387 ctrlKey: ctrlKey === true,
388 shiftKey: shiftKey === true,
389 altKey: altKey === true,
390 repeat: repeat === true,
391 };
392}
393
394export interface HtmlRenderShortcut {
395 readonly key: string;
396 readonly metaKey: boolean;
397 readonly ctrlKey: boolean;
398 readonly shiftKey: boolean;
399 readonly altKey: boolean;
400}
401
402export function htmlRenderShortcutsMessage(
403 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
404 blocked: ReadonlyArray<HtmlRenderShortcut>,
405) {
406 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
407}
408
409export function htmlRenderResult(id: string | number) {
410 return { jsonrpc: "2.0", id, result: {} } as const;
411}
412
413const THEME_FRAGMENT_KEY = "t3-theme";
414
415export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
416 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
417}
418
419const CONTAIN_SCROLL_FRAGMENT_KEY = "t3-contain-scroll";
420
421/** Appended after the theme fragment for a frame whose page must not scroll the host. */
422export const HTML_RENDER_CONTAIN_SCROLL_FRAGMENT = `&${CONTAIN_SCROLL_FRAGMENT_KEY}`;
423
424export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
425 return {
426 jsonrpc: "2.0",
427 method: HOST_CONTEXT_CHANGED_METHOD,
428 params: { theme: theme.appearance, styles: { variables: theme.variables } },
429 } as const;
430}
431
432const BASE_CSS =
433 "html{box-sizing:border-box;padding:8px;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}" +
434 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
435 // Focus outlines paint inside the element, so the frame edge never clips them.
436 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
437 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
438
439function rootRule(theme: HtmlRenderTheme): string {
440 const declarations = Object.entries(theme.variables)
441 .map(([name, value]) => `${name}:${value};`)
442 .join("");
443 return `:root{color-scheme:${theme.appearance};${declarations}}`;
444}
445
446// Native scrollIntoView also scrolls every scroller outside a framed page, such as the chat around an
447// inline render. In a contained frame, it scrolls each scroller inside the page and then the page's own
448// viewport, innermost first, aligning the target as the browser would (block, inline, scroll-margin,
449// scroll-padding, clamped offsets), and stops there. A fixed target or ancestor leaves the viewport alone.
450const CONTAINED_SCROLL_INTO_VIEW = `Element.prototype.scrollIntoView=function(v){var o=v!==null&&(typeof v==="object"||typeof v==="function")?v:{block:v===undefined||v===null||v?"start":"end"},B=o.block||"start",I=o.inline||"nearest",H=o.behavior||"auto",m=function(z){return parseFloat(z)||0;},g=getComputedStyle(this),r=this.getBoundingClientRect(),t=r.top-m(g.scrollMarginTop),b=r.bottom+m(g.scrollMarginBottom),l=r.left-m(g.scrollMarginLeft),R=r.right+m(g.scrollMarginRight),x=0,y=0,e=this,f=g.position==="fixed",d=function(a,z,lo,hi,k){var L=z-a>hi-lo;return k==="start"?a-lo:k==="end"?z-hi:k==="center"?(a+z-lo-hi)/2:a<lo&&z>hi?0:a<lo?L?z-hi:a-lo:z>hi?L?a-lo:z-hi:0;},w=function(top,left,c,s,go){var p=function(n){return m(s["scrollPadding"+n]);},n=s.direction==="rtl"?c.clientWidth-c.scrollWidth:0,dy=d(t-y,b-y,top+p("Top"),top+c.clientHeight-p("Bottom"),B),dx=d(l-x,R-x,left+p("Left"),left+c.clientWidth-p("Right"),I);dy=Math.max(-c.scrollTop,Math.min(c.scrollHeight-c.clientHeight-c.scrollTop,dy));dx=Math.max(n-c.scrollLeft,Math.min(n+c.scrollWidth-c.clientWidth-c.scrollLeft,dx));if(dx||dy)go({left:dx,top:dy,behavior:H});x+=dx;y+=dy;},u=document.scrollingElement||document.documentElement;while(!f){e=e.parentElement||(e.getRootNode&&e.getRootNode().host);if(!e)break;if(e===u||e===document.documentElement)continue;var h=getComputedStyle(document.documentElement),s=getComputedStyle(e),c=e.getBoundingClientRect();if(e===document.body&&h.overflowX+h.overflowY==="visiblevisible")continue;if(/auto|scroll|hidden/.test(s.overflowX+s.overflowY))w(c.top+e.clientTop,c.left+e.clientLeft,e,s,e.scrollBy.bind(e));f=s.position==="fixed";}if(!f)w(0,0,u,getComputedStyle(u),window.scrollBy.bind(window));};`;
451
452const openImageListener = (post: (message: string) => string) =>
453 `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(){var g=[],i=-1;if(e.defaultPrevented)return;Array.prototype.forEach.call(document.images,function(m){var v=m.currentSrc||m.src;if(!v||m.closest("a[href],button"))return;if(m===t)i=g.length;g.push({src:v,name:m.alt||m.title||""});});${post(`{jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||"",images:g,index:i}}`)};});});`;
454
455// Apply overridable theme CSS before paint and strip the fragment before routing; framed navigation uses the client.
456// Forward shortcuts after page handlers; text fields retain their keys.
457const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0,P=/[#&]${CONTAIN_SCROLL_FRAGMENT_KEY}(?:&|$)/.test(location.hash);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);document.addEventListener("click",function(e){var t=e.composedPath()[0],l=t&&t.closest?t.closest("label,a[href],button,input,select,textarea"):null,c=l&&l.tagName==="LABEL"?l.control:null;if(e.isTrusted&&c&&document.activeElement!==c)c.focus({preventScroll:true});},true);if(window.parent!==window){if(P){${CONTAINED_SCROLL_INTO_VIEW}}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);${openImageListener((message) => `window.parent.postMessage(${message},"*")`)}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():"",l==="+"&&!e.shiftKey&&!e.altKey&&!/^Digit/.test(c)?"":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);}})();`;
458
459/**
460 * A native WebView loads the render as its top page, where the bootstrap's frame bridge stays off.
461 * Inject this there and read its messages with `readHtmlRenderImageRequest`.
462 */
463export const HTML_RENDER_NATIVE_OPEN_IMAGE_SCRIPT = `(function(){${openImageListener((message) => `window.ReactNativeWebView.postMessage(JSON.stringify(${message}))`)}})();true;`;
464
465// The tag patterns below stop at the next `<` outside a quoted value, so matching stays linear in
466// the length of the document.
467function hasViewportMeta(markup: string): boolean {
468 for (const [, attrs = ""] of markup.matchAll(/<meta(?=[\s/])((?:[^"'<>]|"[^"]*"|'[^']*')*)>/gi)) {
469 for (const [, attrName, doubleQuoted, singleQuoted, unquoted] of attrs.matchAll(
470 /([^\s"'/<=>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g,
471 )) {
472 if (attrName?.toLowerCase() === "name") {
473 const value = doubleQuoted ?? singleQuoted ?? unquoted;
474 if (value?.toLowerCase() === "viewport") return true;
475 break;
476 }
477 }
478 }
479 return false;
480}
481
482function bootstrapMarkup(markup: string): string {
483 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
484 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
485 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
486 return [
487 /<meta\s[^<>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
488 hasViewportMeta(markup)
489 ? ""
490 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
491 `<style id="t3-theme">${defaultCss}</style>`,
492 `<script>${BOOTSTRAP_SCRIPT}</script>`,
493 ].join("");
494}
495
496// Blank inert content without shifting offsets so it cannot receive the bootstrap.
497const blankNonMarkup = (html: string) => {
498 const scan = html.replace(
499 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
500 (match) => " ".repeat(match.length),
501 );
502 const parts: string[] = [];
503 let depth = 0;
504 let start = 0;
505 let at = 0;
506 for (const match of scan.matchAll(/<(\/?)template(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?\/?>/gi)) {
507 if (!match[1]) {
508 if (depth++ === 0) start = match.index;
509 } else if (depth > 0 && --depth === 0) {
510 const end = match.index + match[0].length;
511 parts.push(scan.slice(at, start), " ".repeat(end - start));
512 at = end;
513 }
514 }
515 if (depth > 0) {
516 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
517 at = scan.length;
518 }
519 parts.push(scan.slice(at));
520 return parts.join("");
521};
522
523export function injectHtmlRenderBootstrap(html: string): string {
524 const scan = blankNonMarkup(html);
525 const markup = bootstrapMarkup(scan);
526 const headOpen = /<head(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?>/i.exec(scan);
527 if (headOpen) {
528 const at = headOpen.index + headOpen[0].length;
529 return html.slice(0, at) + markup + html.slice(at);
530 }
531 const htmlOpen = /<html(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?>/i.exec(scan);
532 if (htmlOpen) {
533 const at = htmlOpen.index + htmlOpen[0].length;
534 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
535 }
536 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
537 if (doctype) {
538 const at = doctype[0].length;
539 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
540 }
541 return `<!doctype html><head>${markup}</head>${html}`;
542}
543
544const FILE_PREVIEW_SCROLL_METHOD = "t3/notifications/file-preview-scroll";
545const FILE_PREVIEW_RESTORE_SCROLL_METHOD = "t3/file-preview/restore-scroll";
546const FILE_PREVIEW_SCROLL_RESTORED_METHOD = "t3/notifications/file-preview-scroll-restored";
547
548export interface FilePreviewScroll {
549 readonly x: number;
550 readonly y: number;
551}
552
553/**
554 * Appended after a served workspace page so it lands at the end of the body without changing
555 * the doctype. A preview frame is an opaque origin, so only the page can report and restore its
556 * scroll position across the reload that follows each workspace change.
557 */
558export const FILE_PREVIEW_SCROLL_SCRIPT = `<script>(function(){var p=window.parent,f=0;if(p===window)return;addEventListener("scroll",function(){if(!f)f=requestAnimationFrame(function(){f=0;p.postMessage({jsonrpc:"2.0",method:${JSON.stringify(FILE_PREVIEW_SCROLL_METHOD)},params:{x:scrollX,y:scrollY}},"*");});},{passive:true});addEventListener("message",function(e){var d=e.data,q=d&&d.params;if(e.source!==p||!d||d.jsonrpc!=="2.0"||d.method!==${JSON.stringify(FILE_PREVIEW_RESTORE_SCROLL_METHOD)}||!q||typeof q.x!=="number"||typeof q.y!=="number")return;scrollTo({left:q.x,top:q.y,behavior:"instant"});p.postMessage({jsonrpc:"2.0",method:${JSON.stringify(FILE_PREVIEW_SCROLL_RESTORED_METHOD)}},"*");});})();</script>`;
559
560export function readFilePreviewScroll(data: unknown): FilePreviewScroll | undefined {
561 if (typeof data !== "object" || data === null) return undefined;
562 const { jsonrpc, method, params } = data as Record<string, unknown>;
563 if (jsonrpc !== "2.0" || method !== FILE_PREVIEW_SCROLL_METHOD) return undefined;
564 if (typeof params !== "object" || params === null) return undefined;
565 const { x, y } = params as Record<string, unknown>;
566 return typeof x === "number" && Number.isFinite(x) && typeof y === "number" && Number.isFinite(y)
567 ? { x, y }
568 : undefined;
569}
570
571export function isFilePreviewScrollRestored(data: unknown): boolean {
572 return (
573 typeof data === "object" &&
574 data !== null &&
575 (data as Record<string, unknown>).jsonrpc === "2.0" &&
576 (data as Record<string, unknown>).method === FILE_PREVIEW_SCROLL_RESTORED_METHOD
577 );
578}
579
580export function filePreviewRestoreScrollMessage(scroll: FilePreviewScroll) {
581 return {
582 jsonrpc: "2.0",
583 method: FILE_PREVIEW_RESTORE_SCROLL_METHOD,
584 params: { x: scroll.x, y: scroll.y },
585 } as const;
586}