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

htmlRender.ts

457 lines22.4 KB

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