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 const high = above === -1 ? heights.length - 1 : above;
89 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
90 return Math.max(heights[low]![1], heights[high]![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
175/** Uses app tokens, except --accent is the brand color rather than a neutral hover surface. */
176export function htmlRenderTheme(
177 colors: ThemeColors,
178 appearance: ThemeAppearance,
179 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
180): HtmlRenderTheme {
181 const fixed = FIXED_COLORS[appearance];
182 return {
183 appearance,
184 variables: {
185 "--background": colors.canvas,
186 "--foreground": colors.text,
187 "--muted": colors.muted,
188 "--muted-foreground": colors.mutedForeground,
189 "--card": colors.surface,
190 "--card-foreground": colors.text,
191 "--popover": colors.surfaceOverlay,
192 "--popover-foreground": colors.text,
193 "--secondary": colors.secondary,
194 "--secondary-foreground": colors.secondaryForeground,
195 "--border": colors.border,
196 "--input": colors.input,
197 "--ring": colors.focus,
198 "--primary": colors.messageAction,
199 "--primary-foreground": colors.messageActionForeground,
200 "--accent": colors.accent,
201 "--accent-foreground": colors.accentForeground,
202 "--accent-surface": colors.accentSurface,
203 "--accent-surface-foreground": colors.accentSurfaceForeground,
204 "--destructive": colors.error,
205 "--destructive-foreground": colors.errorForeground,
206 "--destructive-surface": colors.errorSurface,
207 "--warning": colors.warning,
208 "--warning-foreground": colors.warningForeground,
209 "--warning-surface": colors.warningSurface,
210 "--success": fixed.success,
211 "--success-foreground": fixed.successForeground,
212 "--info": fixed.info,
213 "--info-foreground": fixed.infoForeground,
214 "--code-background": colors.codeBackground,
215 "--code-foreground": colors.codeForeground,
216 "--chart-1": colors.accent,
217 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
218 "--radius": "0.625rem",
219 "--font-sans": fonts.sans,
220 "--font-mono": fonts.mono,
221 },
222 };
223}
224
225export const HTML_RENDER_THEME_GUIDE = [
226 "Use theme CSS variables on :root, not fixed colors:",
227 "--background, --foreground, --muted, --card, --popover, --secondary, --border, --ring, --primary, --accent, --destructive, --warning, --success, --info, --code-background",
228 "(most have a matching -foreground; accent, destructive, and warning also have -surface),",
229 "--chart-1 to --chart-6, --radius, --font-sans, --font-mono.",
230 "The base sheet sets background, text, and font.",
231].join(" ");
232
233export const HTML_RENDER_LAYOUT_GUIDE = [
234 `Frame width is reply width (${HTML_RENDER_COLUMN_WIDTH}px desktop, about 360px phones), on the thread background.`,
235 "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.",
236 "T3 adds an overridable 8px html gutter for selection rings and shadows. Use fluid widths within it.",
237 "A box that needs its own background gets 16px padding and var(--radius) corners. Give charts fixed pixel heights.",
238 "Let content set the height. Do not use vh units or height:100% on html or body. Both are rejected or loop.",
239].join(" ");
240
241const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
242const OPEN_LINK_METHOD = "ui/open-link";
243const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
244// Custom bridge forwards app shortcuts because focused frames otherwise capture them.
245const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
246const KEY_DOWN_METHOD = "t3/notifications/keydown";
247const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
248
249export function readHtmlRenderContentHeight(data: unknown): number | undefined {
250 if (typeof data !== "object" || data === null) return undefined;
251 const { jsonrpc, method, params } = data as Record<string, unknown>;
252 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
253 const height =
254 typeof params === "object" && params !== null
255 ? (params as { height?: unknown }).height
256 : undefined;
257 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
258}
259
260export function readHtmlRenderLinkRequest(data: unknown):
261 | {
262 readonly id: string | number;
263 readonly url: string;
264 readonly metaKey: boolean;
265 readonly ctrlKey: boolean;
266 }
267 | undefined {
268 if (typeof data !== "object" || data === null) return undefined;
269 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
270 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
271 if (typeof id !== "string" && typeof id !== "number") return undefined;
272 if (typeof params !== "object" || params === null) return undefined;
273 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
274 return typeof url === "string" && /^https?:\/\//i.test(url)
275 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
276 : undefined;
277}
278
279interface HtmlRenderImage {
280 readonly src: string;
281 readonly name: string;
282}
283
284function readHtmlRenderImage(src: unknown, name: unknown): HtmlRenderImage | undefined {
285 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
286 const trimmed = typeof name === "string" ? name.trim() : "";
287 // The page sends any alt text; never end the label on half an emoji.
288 const last = trimmed.charCodeAt(HTML_RENDER_MAX_TITLE_LENGTH - 1);
289 const end = HTML_RENDER_MAX_TITLE_LENGTH - (last >= 0xd800 && last <= 0xdbff ? 1 : 0);
290 const label = trimmed.slice(0, end);
291 return { src, name: label || "Image" };
292}
293
294/**
295 * Published local images arrive as `data:image/` URLs. `images` and `index` carry the
296 * page's other images; a page bootstrapped by an older server sends only `src` and `name`.
297 */
298export function readHtmlRenderImageRequest(
299 data: unknown,
300): { readonly images: ReadonlyArray<HtmlRenderImage>; readonly index: number } | undefined {
301 if (typeof data !== "object" || data === null) return undefined;
302 const { jsonrpc, method, params } = data as Record<string, unknown>;
303 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
304 if (typeof params !== "object" || params === null) return undefined;
305 const { src, name, images, index } = params as Record<string, unknown>;
306 const clicked = readHtmlRenderImage(src, name);
307 if (clicked === undefined) return undefined;
308 const gallery: HtmlRenderImage[] = [];
309 let at = -1;
310 if (Array.isArray(images)) {
311 images.forEach((entry: unknown, position) => {
312 if (typeof entry !== "object" || entry === null) return;
313 const image = readHtmlRenderImage(
314 (entry as Record<string, unknown>).src,
315 (entry as Record<string, unknown>).name,
316 );
317 if (image === undefined) return;
318 if (position === index) at = gallery.length;
319 gallery.push(image);
320 });
321 }
322 return at >= 0 && gallery[at]?.src === clicked.src
323 ? { images: gallery, index: at }
324 : { images: [clicked], index: 0 };
325}
326
327export function readHtmlRenderKeyDown(data: unknown):
328 | {
329 readonly key: string;
330 readonly code: string;
331 readonly metaKey: boolean;
332 readonly ctrlKey: boolean;
333 readonly shiftKey: boolean;
334 readonly altKey: boolean;
335 readonly repeat: boolean;
336 }
337 | undefined {
338 if (typeof data !== "object" || data === null) return undefined;
339 const { jsonrpc, method, params } = data as Record<string, unknown>;
340 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
341 if (typeof params !== "object" || params === null) return undefined;
342 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
343 string,
344 unknown
345 >;
346 if (typeof key !== "string" || typeof code !== "string") return undefined;
347 return {
348 key,
349 code,
350 metaKey: metaKey === true,
351 ctrlKey: ctrlKey === true,
352 shiftKey: shiftKey === true,
353 altKey: altKey === true,
354 repeat: repeat === true,
355 };
356}
357
358export interface HtmlRenderShortcut {
359 readonly key: string;
360 readonly metaKey: boolean;
361 readonly ctrlKey: boolean;
362 readonly shiftKey: boolean;
363 readonly altKey: boolean;
364}
365
366export function htmlRenderShortcutsMessage(
367 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
368 blocked: ReadonlyArray<HtmlRenderShortcut>,
369) {
370 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
371}
372
373export function htmlRenderResult(id: string | number) {
374 return { jsonrpc: "2.0", id, result: {} } as const;
375}
376
377const THEME_FRAGMENT_KEY = "t3-theme";
378
379export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
380 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
381}
382
383const CONTAIN_SCROLL_FRAGMENT_KEY = "t3-contain-scroll";
384
385/** Appended after the theme fragment for a frame whose page must not scroll the host. */
386export const HTML_RENDER_CONTAIN_SCROLL_FRAGMENT = `&${CONTAIN_SCROLL_FRAGMENT_KEY}`;
387
388export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
389 return {
390 jsonrpc: "2.0",
391 method: HOST_CONTEXT_CHANGED_METHOD,
392 params: { theme: theme.appearance, styles: { variables: theme.variables } },
393 } as const;
394}
395
396const BASE_CSS =
397 "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}" +
398 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
399 // Focus outlines paint inside the element, so the frame edge never clips them.
400 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
401 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
402
403function rootRule(theme: HtmlRenderTheme): string {
404 const declarations = Object.entries(theme.variables)
405 .map(([name, value]) => `${name}:${value};`)
406 .join("");
407 return `:root{color-scheme:${theme.appearance};${declarations}}`;
408}
409
410// Native scrollIntoView also scrolls every scroller outside a framed page, such as the chat around an
411// inline render. In a contained frame, it scrolls each scroller inside the page and then the page's own
412// viewport, innermost first, aligning the target as the browser would (block, inline, scroll-margin,
413// scroll-padding, clamped offsets), and stops there. A fixed target or ancestor leaves the viewport alone.
414const 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));};`;
415
416// Apply overridable theme CSS before paint and strip the fragment before routing; framed navigation uses the client.
417// Forward shortcuts after page handlers; text fields retain their keys.
418const 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);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||""});});window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||"",images:g,index:i}},"*");});});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);}})();`;
419
420// The tag patterns below stop at the next `<` outside a quoted value, so matching stays linear in
421// the length of the document.
422function bootstrapMarkup(markup: string): string {
423 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
424 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
425 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
426 return [
427 /<meta\s[^<>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
428 /<meta\s(?:[^"'<>]|"[^"]*"|'[^']*')*name\s*=\s*["']?viewport/i.test(markup)
429 ? ""
430 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
431 `<style id="t3-theme">${defaultCss}</style>`,
432 `<script>${BOOTSTRAP_SCRIPT}</script>`,
433 ].join("");
434}
435
436// Blank inert content without shifting offsets so it cannot receive the bootstrap.
437const blankNonMarkup = (html: string) => {
438 const scan = html.replace(
439 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
440 (match) => " ".repeat(match.length),
441 );
442 const parts: string[] = [];
443 let depth = 0;
444 let start = 0;
445 let at = 0;
446 for (const match of scan.matchAll(/<(\/?)template(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?\/?>/gi)) {
447 if (!match[1]) {
448 if (depth++ === 0) start = match.index;
449 } else if (depth > 0 && --depth === 0) {
450 const end = match.index + match[0].length;
451 parts.push(scan.slice(at, start), " ".repeat(end - start));
452 at = end;
453 }
454 }
455 if (depth > 0) {
456 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
457 at = scan.length;
458 }
459 parts.push(scan.slice(at));
460 return parts.join("");
461};
462
463export function injectHtmlRenderBootstrap(html: string): string {
464 const scan = blankNonMarkup(html);
465 const markup = bootstrapMarkup(scan);
466 const headOpen = /<head(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?>/i.exec(scan);
467 if (headOpen) {
468 const at = headOpen.index + headOpen[0].length;
469 return html.slice(0, at) + markup + html.slice(at);
470 }
471 const htmlOpen = /<html(?:\s(?:[^"'<>]|"[^"]*"|'[^']*')*)?>/i.exec(scan);
472 if (htmlOpen) {
473 const at = htmlOpen.index + htmlOpen[0].length;
474 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
475 }
476 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
477 if (doctype) {
478 const at = doctype[0].length;
479 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
480 }
481 return `<!doctype html><head>${markup}</head>${html}`;
482}
483
484const FILE_PREVIEW_SCROLL_METHOD = "t3/notifications/file-preview-scroll";
485const FILE_PREVIEW_RESTORE_SCROLL_METHOD = "t3/file-preview/restore-scroll";
486const FILE_PREVIEW_SCROLL_RESTORED_METHOD = "t3/notifications/file-preview-scroll-restored";
487
488export interface FilePreviewScroll {
489 readonly x: number;
490 readonly y: number;
491}
492
493/**
494 * Appended after a served workspace page so it lands at the end of the body without changing
495 * the doctype. A preview frame is an opaque origin, so only the page can report and restore its
496 * scroll position across the reload that follows each workspace change.
497 */
498export 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>`;
499
500export function readFilePreviewScroll(data: unknown): FilePreviewScroll | undefined {
501 if (typeof data !== "object" || data === null) return undefined;
502 const { jsonrpc, method, params } = data as Record<string, unknown>;
503 if (jsonrpc !== "2.0" || method !== FILE_PREVIEW_SCROLL_METHOD) return undefined;
504 if (typeof params !== "object" || params === null) return undefined;
505 const { x, y } = params as Record<string, unknown>;
506 return typeof x === "number" && Number.isFinite(x) && typeof y === "number" && Number.isFinite(y)
507 ? { x, y }
508 : undefined;
509}
510
511export function isFilePreviewScrollRestored(data: unknown): boolean {
512 return (
513 typeof data === "object" &&
514 data !== null &&
515 (data as Record<string, unknown>).jsonrpc === "2.0" &&
516 (data as Record<string, unknown>).method === FILE_PREVIEW_SCROLL_RESTORED_METHOD
517 );
518}
519
520export function filePreviewRestoreScrollMessage(scroll: FilePreviewScroll) {
521 return {
522 jsonrpc: "2.0",
523 method: FILE_PREVIEW_RESTORE_SCROLL_METHOD,
524 params: { x: scroll.x, y: scroll.y },
525 } as const;
526}