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// The taller of the heights measured at the nearest widths on each side. A
86// breakpoint between two measured widths can make the page as tall as either.
87function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
88 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
89 const high = above === -1 ? heights.length - 1 : above;
90 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
91 return Math.max(heights[low]![1], heights[high]![1]);
92}
93
94/**
95 * A page even a few pixels taller than its frame scrolls inside it and takes
96 * the reader's scroll, so the frame fits the page. A client that measured the
97 * live page passes `contentHeight`, which wins over the agent's height: client
98 * fonts often wrap the page taller than the server or agent measured it.
99 */
100export function htmlRenderFrameHeight(
101 reference: HtmlRenderReference,
102 width: number,
103 contentHeight?: number,
104) {
105 if (contentHeight !== undefined) {
106 return Math.min(
107 HTML_RENDER_MAX_FIT_HEIGHT,
108 Math.max(HTML_RENDER_MIN_HEIGHT, Math.ceil(contentHeight)),
109 );
110 }
111 const heights = reference.heights;
112 if (heights === undefined || heights.length === 0) {
113 return clampHtmlRenderHeight(reference.height);
114 }
115 const cap =
116 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
117 ? reference.height
118 : HTML_RENDER_MAX_HEIGHT;
119 return clampHtmlRenderHeight(Math.min(cap, measuredHeight(heights, width)));
120}
121
122export function htmlRenderFileName(title: string) {
123 const name = title
124 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
125 .replace(/\s+/g, " ")
126 .trim()
127 .slice(0, 120)
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/**
148 * Arial-metric faces stand in for the system UI fonts readers see, so measured
149 * heights and preview screenshots wrap text close to how a client will.
150 */
151export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
152 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
153 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
154};
155
156export interface HtmlRenderTheme {
157 readonly appearance: ThemeAppearance;
158 readonly variables: Readonly<Record<string, string>>;
159}
160
161const FIXED_COLORS = {
162 light: {
163 success: "#10b981",
164 successForeground: "#047857",
165 info: "#3b82f6",
166 infoForeground: "#1d4ed8",
167 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
168 },
169 dark: {
170 success: "#10b981",
171 successForeground: "#34d399",
172 info: "#3b82f6",
173 infoForeground: "#60a5fa",
174 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
175 },
176} as const;
177
178/**
179 * Names follow the app's own tokens, except `--accent`, which is the theme's
180 * brand color here rather than the app's neutral hover surface.
181 */
182export function htmlRenderTheme(
183 colors: ThemeColors,
184 appearance: ThemeAppearance,
185 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
186): HtmlRenderTheme {
187 const fixed = FIXED_COLORS[appearance];
188 return {
189 appearance,
190 variables: {
191 "--background": colors.canvas,
192 "--foreground": colors.text,
193 "--muted": colors.muted,
194 "--muted-foreground": colors.mutedForeground,
195 "--card": colors.surface,
196 "--card-foreground": colors.text,
197 "--popover": colors.surfaceOverlay,
198 "--popover-foreground": colors.text,
199 "--secondary": colors.secondary,
200 "--secondary-foreground": colors.secondaryForeground,
201 "--border": colors.border,
202 "--input": colors.input,
203 "--ring": colors.focus,
204 "--primary": colors.messageAction,
205 "--primary-foreground": colors.messageActionForeground,
206 "--accent": colors.accent,
207 "--accent-foreground": colors.accentForeground,
208 "--accent-surface": colors.accentSurface,
209 "--accent-surface-foreground": colors.accentSurfaceForeground,
210 "--destructive": colors.error,
211 "--destructive-foreground": colors.errorForeground,
212 "--destructive-surface": colors.errorSurface,
213 "--warning": colors.warning,
214 "--warning-foreground": colors.warningForeground,
215 "--warning-surface": colors.warningSurface,
216 "--success": fixed.success,
217 "--success-foreground": fixed.successForeground,
218 "--info": fixed.info,
219 "--info-foreground": fixed.infoForeground,
220 "--code-background": colors.codeBackground,
221 "--code-foreground": colors.codeForeground,
222 "--chart-1": colors.accent,
223 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
224 "--radius": "0.625rem",
225 "--font-sans": fonts.sans,
226 "--font-mono": fonts.mono,
227 },
228 };
229}
230
231export const HTML_RENDER_THEME_GUIDE = [
232 "T3 injects its active theme as CSS custom properties on :root, and they follow the user's theme and light/dark mode live:",
233 "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
234 "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
235 "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
236 "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
237 "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
238 "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
239 "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.",
240].join(" ");
241
242export const HTML_RENDER_LAYOUT_GUIDE = [
243 `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.`,
244 "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.",
245 "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.",
246 "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.",
247 "Give charts fixed pixel heights rather than heights that scale with width.",
248 "Let content set the page's height. The frame grows to fit the page, so a height that follows the viewport makes it grow again and again: html_preview and html_render reject vh, svh, lvh, and dvh units, and height:100% on html or body has the same problem.",
249].join(" ");
250
251const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
252const OPEN_LINK_METHOD = "ui/open-link";
253const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
254// Not part of MCP Apps: a focused frame keeps its keys from the app, so the
255// client tells the page which chords are app shortcuts and the page passes
256// those on.
257const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
258const KEY_DOWN_METHOD = "t3/notifications/keydown";
259// Not part of MCP Apps: a click on a page image opens it in the app's image viewer.
260const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
261
262export function readHtmlRenderContentHeight(data: unknown): number | undefined {
263 if (typeof data !== "object" || data === null) return undefined;
264 const { jsonrpc, method, params } = data as Record<string, unknown>;
265 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
266 const height =
267 typeof params === "object" && params !== null
268 ? (params as { height?: unknown }).height
269 : undefined;
270 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
271}
272
273export function readHtmlRenderLinkRequest(data: unknown):
274 | {
275 readonly id: string | number;
276 readonly url: string;
277 readonly metaKey: boolean;
278 readonly ctrlKey: boolean;
279 }
280 | undefined {
281 if (typeof data !== "object" || data === null) return undefined;
282 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
283 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
284 if (typeof id !== "string" && typeof id !== "number") return undefined;
285 if (typeof params !== "object" || params === null) return undefined;
286 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
287 return typeof url === "string" && /^https?:\/\//i.test(url)
288 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
289 : undefined;
290}
291
292/**
293 * The image a framed render's reader clicked, if `data` is an open-image
294 * notification for an http(s) or inline image URL. Server-side publishing
295 * inlines local images, so most arrive as `data:image/` URLs.
296 */
297export function readHtmlRenderImageRequest(
298 data: unknown,
299): { readonly src: string; readonly name: string } | undefined {
300 if (typeof data !== "object" || data === null) return undefined;
301 const { jsonrpc, method, params } = data as Record<string, unknown>;
302 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
303 if (typeof params !== "object" || params === null) return undefined;
304 const { src, name } = params as Record<string, unknown>;
305 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
306 const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";
307 return { src, name: label || "Image" };
308}
309
310/** The key a framed render passed on in a `t3/notifications/keydown` notification. */
311export function readHtmlRenderKeyDown(data: unknown):
312 | {
313 readonly key: string;
314 readonly code: string;
315 readonly metaKey: boolean;
316 readonly ctrlKey: boolean;
317 readonly shiftKey: boolean;
318 readonly altKey: boolean;
319 readonly repeat: boolean;
320 }
321 | undefined {
322 if (typeof data !== "object" || data === null) return undefined;
323 const { jsonrpc, method, params } = data as Record<string, unknown>;
324 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
325 if (typeof params !== "object" || params === null) return undefined;
326 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
327 string,
328 unknown
329 >;
330 if (typeof key !== "string" || typeof code !== "string") return undefined;
331 return {
332 key,
333 code,
334 metaKey: metaKey === true,
335 ctrlKey: ctrlKey === true,
336 shiftKey: shiftKey === true,
337 altKey: altKey === true,
338 repeat: repeat === true,
339 };
340}
341
342export interface HtmlRenderShortcut {
343 readonly key: string;
344 readonly metaKey: boolean;
345 readonly ctrlKey: boolean;
346 readonly shiftKey: boolean;
347 readonly altKey: boolean;
348}
349
350export function htmlRenderShortcutsMessage(
351 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
352 blocked: ReadonlyArray<HtmlRenderShortcut>,
353) {
354 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
355}
356
357export function htmlRenderResult(id: string | number) {
358 return { jsonrpc: "2.0", id, result: {} } as const;
359}
360
361const THEME_FRAGMENT_KEY = "t3-theme";
362
363export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
364 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
365}
366
367export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
368 return {
369 jsonrpc: "2.0",
370 method: HOST_CONTEXT_CHANGED_METHOD,
371 params: { theme: theme.appearance, styles: { variables: theme.variables } },
372 } as const;
373}
374
375const BASE_CSS =
376 "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}" +
377 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
378 // Focus outlines paint inside the element, so the frame edge never clips them.
379 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
380 // An image outside a link or button opens in the app's viewer, as chat images do.
381 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
382
383function rootRule(theme: HtmlRenderTheme): string {
384 const declarations = Object.entries(theme.variables)
385 .map(([name, value]) => `${name}:${value};`)
386 .join("");
387 return `:root{color-scheme:${theme.appearance};${declarations}}`;
388}
389
390// Runs synchronously in <head>, before the page's own styles and body, so the
391// first paint is already themed. It rewrites its own <style> element rather
392// than setting inline properties, so a page's later `:root` rules still win,
393// then drops the fragment so a page's own hash routing never sees it. A link
394// the reader clicks to another page never replaces the page inside the thread:
395// a framed page asks its client to open it, and a top-level page (mobile)
396// opens it as a new window, which the client sends to the browser. A plain
397// left click on a framed page's image, outside a link or button and not
398// prevented by any of the page's listeners, asks the client to open the image
399// in its viewer. A framed page also reports its content height, measured as the server measures it,
400// so its client can fit the frame to the page. A chord the client named as an
401// app shortcut is passed on rather than left to the browser, unless a text
402// field has focus or the page handled it: the deciding listener is added while
403// the key dispatches, so it runs after every listener the page has. Keys
404// match as resolveEventKeys reads them, so the client accepts what it claims.
405const 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);}})();`;
406
407function bootstrapMarkup(markup: string): string {
408 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
409 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
410 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
411 return [
412 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
413 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
414 ? ""
415 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
416 `<style id="t3-theme">${defaultCss}</style>`,
417 `<script>${BOOTSTRAP_SCRIPT}</script>`,
418 ].join("");
419}
420
421// Comments, raw text, and template contents are blanked to the same length,
422// so offsets still line up and inert tags cannot receive the bootstrap.
423const blankNonMarkup = (html: string) => {
424 const scan = html.replace(
425 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
426 (match) => " ".repeat(match.length),
427 );
428 const parts: string[] = [];
429 let depth = 0;
430 let start = 0;
431 let at = 0;
432 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
433 if (!match[1]) {
434 if (depth++ === 0) start = match.index;
435 } else if (depth > 0 && --depth === 0) {
436 const end = match.index + match[0].length;
437 parts.push(scan.slice(at, start), " ".repeat(end - start));
438 at = end;
439 }
440 }
441 if (depth > 0) {
442 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
443 at = scan.length;
444 }
445 parts.push(scan.slice(at));
446 return parts.join("");
447};
448
449export function injectHtmlRenderBootstrap(html: string): string {
450 const scan = blankNonMarkup(html);
451 const markup = bootstrapMarkup(scan);
452 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
453 if (headOpen) {
454 const at = headOpen.index + headOpen[0].length;
455 return html.slice(0, at) + markup + html.slice(at);
456 }
457 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
458 if (htmlOpen) {
459 const at = htmlOpen.index + htmlOpen[0].length;
460 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
461 }
462 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
463 if (doctype) {
464 const at = doctype[0].length;
465 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
466 }
467 return `<!doctype html><head>${markup}</head>${html}`;
468}