Official

visuals

HTML pages (html_preview, html_render) and native inline charts, positioned diagrams and sortable tables in agent replies.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install convergence/visuals@0.2.1

Visuals — official plugin

convergence/visuals provides publish_visual for interactive, native visual replies. It ships enabled on a fresh install; an existing install keeps the choice it has, and users can turn it off or on in Settings → Plugins. It starts only when a reply first contains one of its fences and loads Pele only on the first Mermaid fence, so a chat without fences pays nothing. Its only requested permission is tools.provide.

HTML pages (T3 Code's html_preview and html_render)

html.ts holds T3's contract (pingdotgg/t3code b24f0fbb): the tool names, descriptions, limits (HTML 1–512000 UTF-16 units, title 1–200, preview width 240–1600 with 728 by default, frame height 80–2000), the result shapes and messages, the frame-height rule, and the theme bootstrap with Divergence's colours. Both tools are direct, so in code mode they stay tools of their own and the preview's PNG reaches the agent as an MCP image part.

  • html_preview sends the themed page to host/web.preview. With a web view it answers T3's metadata as text and structured content plus the PNG. Without one it is an error, HtmlBackendUnavailable: <raw reason>, with no image, and no screenshot is made up.
  • html_render saves the agent's page unchanged as a html v1 transcript artifact (the host stamps the owner) and answers T3's htmlRender reference and message. Measured heights are not supplied.
  • Inline (html-view.ts) the page is live (ui.webDocument): borderless in the reply, as wide as the column and as tall as the page up to the agent's height, with one small glass Open in panel control. The panel is a detail-pane tab (the convergence/tabs service): the page live again, its Source, Copy and Save (kernel/copy_text, kernel/save_text, both after a click).

The renderer is the system's WKWebView on macOS (crates/host/src/web), so a page behaves as it would in Safari, with the Mac's fonts, the GPU, text input, the clipboard and native pickers. The difference from T3 is that pages are offline: remote URLs and local image paths never load (missingImages lists the paths a page names). On Linux and Windows, which have no web view in this version, the page says so and its source, copy and save still work.

Version 2 supports responsive multi-panel compositions: bar (grouped/stacked/ percent; horizontal/vertical), line, area, scatter/bubble, pie/donut, heatmap, histogram, range/timeline, waterfall and boxplot, plus metrics, text, typed tables and positioned diagrams. document.ts defines the strict, bounded JSON schema; rules.md is the agent-facing reference. Version 1 documents still replay.

Rendering and interaction

Rust/GPUI draws every shape, label, control and floating tooltip. A pinned, DOM-free D3 math subset computes scales, numeric/UTC ticks and paths inside QuickJS; there is no browser, JavaScript UI execution, graph auto-layout, network, file, process or plugin-storage access. math.LICENSES.txt includes provenance and licenses; scripts/bundle-visuals-math.mjs reproduces the readable bundle.

Charts use the native canvas's onResize({width,height}) logical-pixel measurement, not a scaled viewBox. Text remains readable as panels grow or wrap. Compact legends keep original domains, colors and percentage denominators when hidden. Null breaks paths and stays explicitly missing in shared bar inspection.

Hover opens a clamped floating tooltip; click pins/unpins. Arrow keys, Home/End traverse observations, Enter/Space pin, Escape clears inspection. In the expanded overlay Escape unpins first, then closes. Tables retain stable raw row identity, sort nulls last in either direction, paginate and expose full selected values. Diagram node details remain accessible through a native picker.

State and cached geometry belong to each artifact's ctx.state, with separate panels and inline/expanded inspection. Hover does not recompute paths. Native resize reports are change-only and coalesced off-paint. No JavaScript frame loop or render-time notification runs.

Persistence and compatibility

The host owns immutable transcript artifacts. ctx.artifacts.publish persists the complete document independently of the surrounding tool result, including discarded acknowledgements and later code-mode errors. The plugin registers removable visual renderers for versions 1 and 2; Source retains original input and Data retains all raw values, including hidden series and nulls.

This plugin requires the updated native host and canvas resize API. Older hosts without artifact support fail with an explicit update message. Invalid persisted documents keep their readable summary and expose a validation error.

Verification

node --import ./plugins/testing/register.mjs --test plugins/visuals/*.test.ts
pnpm -C plugins typecheck
pnpm -C plugins exec prettier --check 'visuals/**/*.{ts,json,md}'

Geometry tests use asymmetric data and independent numeric expectations; view tests exercise real native element factories and handlers. Native desktop checks and app-owned Metal captures supplement these tests; they do not use a browser.

Permissions in 0.2.1

  • Provide agent tools tools.provideMediumGives tools to agents.Let agents preview and publish HTML pages and bounded visual replies into the current chat

Files

html.ts21.6 KB
// HTML pages ("HTML renders"): the T3 Code contract of html_preview and html_render, in Divergence's
// colours. Limits, descriptions and the theme bootstrap follow T3's packages/shared/src/htmlRender.ts
// (pingdotgg/t3code b24f0fbb). The deliberate difference: pages are offline. Remote URLs and local
// files never load; the host's browser serves the page and the app's own typefaces, nothing else.
import * as z from "zod";

export const HTML_RENDER_MIN_HEIGHT = 80;
export const HTML_RENDER_MAX_HEIGHT = 2000;
export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
export const HTML_MAX_LENGTH = 512_000;
export const HTML_RENDER_COLUMN_WIDTH = 728;
export const HTML_PREVIEW_MIN_WIDTH = 240;
export const HTML_PREVIEW_MAX_WIDTH = 1600;

/** T3's orchestration instruction, word for word. */
export const HTML_RENDER_INSTRUCTION =
  "When a chart, table, diagram, image collage, or mockup would say more than prose, build a self-contained HTML page, check it with `html_preview`, then publish it with `html_render` before your final reply. The reader sees the page above that reply, so don't announce or restate it; add only what it doesn't say.";

/** T3's `html_render` result message, word for word. */
export const HTML_RENDER_MESSAGE =
  "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say.";

const PAGE_RULES =
  "Write one self-contained document with inline <style> and <script>. Pages are offline: remote http(s) URLs (such as a CDN chart library) and local file paths do not load, so inline libraries and embed images as data: URLs.";

export const HTML_RENDER_THEME_GUIDE = [
  "Divergence injects its theme as CSS custom properties on :root, for the appearance the page is shown in:",
  "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
  "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
  "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
  "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
  "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
  "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
  "Each -foreground is the text colour on its solid colour (--warning-foreground on --warning); text on --destructive-surface or --warning-surface uses --foreground, and on --accent-surface uses --accent-surface-foreground.",
  "--font-sans is the app's own interface face (Inter) and --font-mono its code face (JetBrains Mono); both are served offline, so a page that inherits them is set like the app around it.",
  "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.",
].join(" ");

export const HTML_RENDER_LAYOUT_GUIDE = [
  `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), and its left edge lines up with your reply text.`,
  "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.",
  "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.",
  "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.",
  "Give charts fixed pixel heights rather than heights that scale with width.",
  "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.",
].join(" ");

/** How a page should look in a reply when the user gives no direction: the calm report, an inspector only when selection does work. */
export const HTML_RENDER_DESIGN_GUIDE = [
  "Design: when the user gives no visual direction, default to a calm inline report. Lead with a short title and one-sentence takeaway, then the content itself:",
  "key figures as plain large numbers with a muted label (no box around each), a chart with a fixed height, light gridlines and its legend in the chart's header row, and a plain table with a header row and no cell borders.",
  "By default keep surfaces flat and unboxed: no stacked or nested cards, outlines around every section, glows, gradients or drop shadows.",
  "When the user asks for a specific look (a dashboard, cards, a mockup of a particular screen or brand), build that look instead; these defaults never override a requested design.",
  "Use the theme variables for every colour; spend --chart-* and semantic colours on data and status, not decoration.",
  "Use an interactive workspace (a selectable list beside a detail panel, tabs or filters) only when selecting or filtering does real work on the data, and make every control actually change what is shown.",
  "Keep controls compact and labelled, keep text readable at about 360px wide, and label made-up or sample data as illustrative.",
  "Craft: about 32px between sections and 8px between a section heading and its content; type inherits --font-sans with natural letter spacing (no negative tracking, no spaced or uppercase labels) in a compact hierarchy: the title about 18px and section headings about 14-15px, both medium weight (500), body 14px regular, captions 12px in --muted-foreground, and only the key figures larger; numbers in tables, axes and figures use font-variant-numeric: tabular-nums and right alignment; keep each number with its unit on one line (white-space: nowrap) and let a group of figures wrap as whole items, never splitting a value from its unit.",
  "Frame charts deliberately: category labels in one aligned column, gridlines and axis labels placed from the same scale so every tick sits on its gridline, quiet gridlines in --border, bars no thicker than about 12px, units in the chart's caption rather than as an extra tick label, and no empty axis when nothing is plotted.",
  "Surfaces: a detail panel that needs its own background uses --card or --muted with 16px padding; keep --accent-surface for the selected row or a small badge, never a large panel.",
  "Narrow widths: put a section's caption or unit on its own line directly under its heading (left-aligned, not pushed to the right edge), keep counts and controls with the content they describe, let figures wrap to two per row below about 480px, and keep every line of text inside the column with nothing overflowing or clipped. The outermost element still has no horizontal padding at any width: alignment with the reply text wins.",
  "Filters: put the filter next to the content it narrows. When it narrows the chart and table, either recompute the takeaway and key figures for what is visible or label them as overall; show the active scope (for example \"4 of 6 services matching 'at'\"), and never let a sentence name an item the filter hides: a takeaway that stays fixed must say it is overall (\"Overall, …\").",
  "Empty states: when a filter matches nothing, say so where the content was and offer a button that clears the filter; every other region, the detail panel and any caption or hint that offers an action included, then tells the reader to change or clear the filter, never to select an item that is not there, and the usual hint returns when items do.",
  "Check before html_render: preview at the default width and again with width 360; for an interactive page, also preview a copy with a temporary script that drives its own controls (a matching filter, a filter that matches nothing, a selected row) and console.logs the visible text, then publish without that script.",
  "html_render's height is the frame's maximum, not a chart height: pass the contentHeight html_preview reported at the default width, or more, unless you intend the page to scroll inside a shorter frame.",
].join(" ");

export const HTML_PREVIEW_DESCRIPTION = `Render an HTML page in Divergence's confined offline browser and get back a PNG screenshot, contentHeight (the height the page needs at this width), and its console output: log, info, warning, error, and uncaught exceptions, with stack traces pointing into page.html. console.log is a fine way to report your own checks. Use it to check and iterate on a page before html_render. If this machine has no confined browser, the tool says so and returns no image; html_render still saves the page. ${PAGE_RULES} The page gets the theme variables, layout and design described in html_render.`;

export const HTML_RENDER_DESCRIPTION = `Show a finished HTML page (chart, table, diagram, collage, mockup) inline in this thread, above your final text reply; call it before writing that reply. The reader already sees the page, so the reply should not announce it, say where it is, or restate it: add only what the page doesn't say. Preview with html_preview first. Divergence fits the frame to the page's height at each reader's width. A height below the page's contentHeight caps the frame there, and the rest scrolls inside it. ${PAGE_RULES} ${HTML_RENDER_LAYOUT_GUIDE} ${HTML_RENDER_DESIGN_GUIDE} ${HTML_RENDER_THEME_GUIDE}`;

/** JavaScript string length is UTF-16 code units, as T3 counts. */
const html = z.string().min(1).max(HTML_MAX_LENGTH).describe("A complete, self-contained HTML document.");

export const htmlPreviewInput = z.strictObject({
  html,
  width: z
    .number()
    .int()
    .optional()
    .describe(
      `Viewport width in CSS pixels, ${HTML_PREVIEW_MIN_WIDTH}-${HTML_PREVIEW_MAX_WIDTH}. Defaults to ${HTML_RENDER_COLUMN_WIDTH}, the reply column; use about 390 to check phones.`,
    ),
  appearance: z.enum(["dark", "light"]).optional().describe("Theme to preview. Defaults to dark."),
});

export const consoleMessage = z.strictObject({
  level: z.enum(["log", "info", "warning", "error"]),
  text: z.string(),
});

/** What html_preview's text and structured content say; the PNG is the image part. */
export const htmlPreviewOutput = z.strictObject({
  width: z.number().int(),
  contentHeight: z.number().int(),
  capturedHeight: z.number().int(),
  consoleMessages: z.array(consoleMessage),
  missingImages: z.array(z.string()).optional(),
  screenshot: z.strictObject({
    mimeType: z.literal("image/png"),
    width: z.number().int(),
    height: z.number().int(),
  }),
});

export const htmlRenderInput = z.strictObject({
  html,
  title: z.string().min(1).max(HTML_RENDER_MAX_TITLE_LENGTH).describe("Short name for the page."),
  height: z
    .number()
    .int()
    .describe(
      `The frame height in CSS pixels, ${HTML_RENDER_MIN_HEIGHT}-${HTML_RENDER_MAX_HEIGHT}. Use html_preview's contentHeight, or less to make long content scroll inside the frame.`,
    ),
});

export const htmlRenderReference = z.strictObject({
  attachmentId: z.string().min(1),
  title: z.string(),
  height: z.number(),
  heights: z.array(z.tuple([z.number().int(), z.number().int()])).optional(),
});

export const htmlRenderOutput = z.strictObject({
  htmlRender: htmlRenderReference,
  message: z.string(),
});

/** The persisted document: the page as the agent wrote it, never rewritten. */
export const htmlDocument = z.strictObject({
  html,
  title: z.string().min(1).max(HTML_RENDER_MAX_TITLE_LENGTH),
  height: z.number().int().min(HTML_RENDER_MIN_HEIGHT).max(HTML_RENDER_MAX_HEIGHT),
  heights: z.array(z.tuple([z.number().int(), z.number().int()])).optional(),
});
export type HtmlDocument = z.infer<typeof htmlDocument>;

export function clampHtmlRenderHeight(height: number): number {
  return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
}

export function clampPreviewWidth(width: number | undefined): number {
  return Math.min(
    HTML_PREVIEW_MAX_WIDTH,
    Math.max(HTML_PREVIEW_MIN_WIDTH, Math.round(width ?? HTML_RENDER_COLUMN_WIDTH)),
  );
}

/** T3's frame height rule for a page at a frame width. */
export function htmlRenderFrameHeight(document: HtmlDocument, width: number, contentHeight?: number): number {
  const heights = document.heights;
  if (heights === undefined || heights.length === 0)
    return clampHtmlRenderHeight(Math.min(document.height, contentHeight ?? document.height));
  const measured = (at: number) => {
    const above = heights.findIndex(([measuredWidth]) => measuredWidth >= at);
    const high = above === -1 ? heights.length - 1 : above;
    const low = heights[high]![0] === at ? high : Math.max(0, high - 1);
    return Math.max(heights[low]![1], heights[high]![1]);
  };
  const cap = measured(HTML_RENDER_COLUMN_WIDTH) > document.height ? document.height : HTML_RENDER_MAX_HEIGHT;
  return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measured(width)));
}

/** A readable download name: the title without characters file systems reject. */
export function htmlRenderFileName(title: string): string {
  const name = title
    .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 120)
    .trim();
  return `${name || "Page"}.html`;
}

const IMAGE_EXTENSIONS = "png|jpg|jpeg|gif|webp|avif|svg|bmp|ico";
// T3's pattern: an absolute image path that is a whole quoted string or an unquoted CSS url(...).
const LOCAL_IMAGE_PATTERN = new RegExp(
  String.raw`(["'\x60])((?:/(?!/)|[a-z]:[\\/])(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))\1` +
    String.raw`|url\(\s*((?:/(?!/)|[a-z]:[\\/])[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))\s*\)`,
  "gi",
);

/** Local image paths the page names. Offline pages never read them; they show as broken images. */
export function missingImages(page: string): string[] {
  return [...new Set(Array.from(page.matchAll(LOCAL_IMAGE_PATTERN), (match) => match[2] ?? match[3]!))];
}

// The Divergence colours (plugins/themes/convergence.ts, from crates/kernel/themes/convergence.json).
const PALETTES = {
  dark: {
    background: "#0a1224",
    foreground: "#f2f4f8",
    muted: "#1a2436",
    mutedForeground: "#9aa4b5",
    card: "#121c30",
    popover: "#121a28",
    secondary: "#121c30",
    secondaryForeground: "#f2f4f8",
    border: "#2a3446",
    input: "#2a3446",
    ring: "#3f5778",
    primary: "#fafafa",
    primaryForeground: "#171717",
    accent: "#5b9cff",
    accentForeground: "#ffffff",
    accentSurface: "#25466f",
    accentSurfaceForeground: "#f2f4f8",
    destructive: "#e05a4f",
    destructiveForeground: "#ffffff",
    destructiveSurface: "#3a1d22",
    warning: "#e0b23a",
    warningForeground: "#1a1200",
    warningSurface: "#3a3120",
    success: "#3fb97c",
    successForeground: "#062a16",
    info: "#5b9cff",
    infoForeground: "#ffffff",
    codeBackground: "#121c30",
    codeForeground: "#f2f4f8",
    chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
  },
  light: {
    background: "#f3f7fd",
    foreground: "#0a0a0a",
    muted: "#e6ecf5",
    mutedForeground: "#556070",
    card: "#ffffff",
    popover: "#ffffff",
    secondary: "#fcfeff",
    secondaryForeground: "#171717",
    border: "#d7dfe6",
    input: "#d7dfe6",
    ring: "#b4c0cf",
    primary: "#171717",
    primaryForeground: "#fafafa",
    accent: "#4f8ef7",
    accentForeground: "#ffffff",
    accentSurface: "#dfe9f5",
    accentSurfaceForeground: "#0a0a0a",
    destructive: "#d4413b",
    destructiveForeground: "#ffffff",
    destructiveSurface: "#fbe4e2",
    warning: "#d9a520",
    warningForeground: "#1a1200",
    warningSurface: "#fbf1d6",
    success: "#2ea672",
    successForeground: "#ffffff",
    info: "#4f8ef7",
    infoForeground: "#ffffff",
    codeBackground: "#ffffff",
    codeForeground: "#0a0a0a",
    chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
  },
} as const;

// The app's bundled faces, served offline by the host at FONTS_URL (crates/host/src/web/page.rs FONTS):
// [file, family, weight, italic].
const FONTS_URL = "http://page.localhost/fonts/";
const FONT_FILES = [
  ["Inter-Regular.otf", "Inter", 400, false],
  ["Inter-Italic.otf", "Inter", 400, true],
  ["Inter-Medium.otf", "Inter", 500, false],
  ["Inter-MediumItalic.otf", "Inter", 500, true],
  ["Inter-SemiBold.otf", "Inter", 600, false],
  ["Inter-SemiBoldItalic.otf", "Inter", 600, true],
  ["Inter-Bold.otf", "Inter", 700, false],
  ["Inter-BoldItalic.otf", "Inter", 700, true],
  ["JetBrainsMono-Regular.ttf", "JetBrains Mono", 400, false],
  ["JetBrainsMono-Italic.ttf", "JetBrains Mono", 400, true],
  ["JetBrainsMono-Bold.ttf", "JetBrains Mono", 700, false],
  ["JetBrainsMono-BoldItalic.ttf", "JetBrains Mono", 700, true],
] as const;

/** The `@font-face` rules for the app's faces; a face downloads only when the page uses it. */
export const FONT_FACES = FONT_FILES.map(
  ([file, family, weight, italic]) =>
    `@font-face{font-family:"${family}";font-style:${italic ? "italic" : "normal"};font-weight:${weight};src:url(${FONTS_URL}${file})}`,
).join("");

const FONTS = {
  sans: '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
  mono: '"JetBrains Mono", "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
};

export type Appearance = "dark" | "light";

/** The CSS variables a page styles against, as T3 names them. */
export function themeVariables(appearance: Appearance): Record<string, string> {
  const c = PALETTES[appearance];
  return {
    "--background": c.background,
    "--foreground": c.foreground,
    "--muted": c.muted,
    "--muted-foreground": c.mutedForeground,
    "--card": c.card,
    "--card-foreground": c.foreground,
    "--popover": c.popover,
    "--popover-foreground": c.foreground,
    "--secondary": c.secondary,
    "--secondary-foreground": c.secondaryForeground,
    "--border": c.border,
    "--input": c.input,
    "--ring": c.ring,
    "--primary": c.primary,
    "--primary-foreground": c.primaryForeground,
    "--accent": c.accent,
    "--accent-foreground": c.accentForeground,
    "--accent-surface": c.accentSurface,
    "--accent-surface-foreground": c.accentSurfaceForeground,
    "--destructive": c.destructive,
    "--destructive-foreground": c.destructiveForeground,
    "--destructive-surface": c.destructiveSurface,
    "--warning": c.warning,
    "--warning-foreground": c.warningForeground,
    "--warning-surface": c.warningSurface,
    "--success": c.success,
    "--success-foreground": c.successForeground,
    "--info": c.info,
    "--info-foreground": c.infoForeground,
    "--code-background": c.codeBackground,
    "--code-foreground": c.codeForeground,
    "--chart-1": c.accent,
    ...Object.fromEntries(c.chart.map((color, index) => [`--chart-${index + 2}`, color])),
    "--radius": "0.625rem",
    "--font-sans": FONTS.sans,
    "--font-mono": FONTS.mono,
  };
}

// The frame scrolls a page taller than itself; a scrollbar inside a reply reads as a box, so it is hidden.
const BASE_CSS =
  FONT_FACES +
  "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}" +
  "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}";

function bootstrapMarkup(markup: string, appearance: Appearance): string {
  const declarations = Object.entries(themeVariables(appearance))
    .map(([name, value]) => `${name}:${value};`)
    .join("");
  return [
    /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
    /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
      ? ""
      : '<meta name="viewport" content="width=device-width, initial-scale=1">',
    `<style id="divergence-theme">:root{color-scheme:${appearance};${declarations}}${BASE_CSS}</style>`,
  ].join("");
}

// Comments, raw text and template contents are blanked to the same length, so offsets line up and
// inert tags cannot receive the bootstrap (T3's scan).
function blankNonMarkup(page: string): string {
  const scan = page.replace(
    /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
    (match) => " ".repeat(match.length),
  );
  const parts: string[] = [];
  let depth = 0;
  let start = 0;
  let at = 0;
  for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
    if (!match[1]) {
      if (depth++ === 0) start = match.index;
    } else if (depth > 0 && --depth === 0) {
      const end = match.index + match[0].length;
      parts.push(scan.slice(at, start), " ".repeat(end - start));
      at = end;
    }
  }
  if (depth > 0) {
    parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
    at = scan.length;
  }
  parts.push(scan.slice(at));
  return parts.join("");
}

/** The theme at the start of the head, so the page's own styles come after it. */
export function injectThemeBootstrap(page: string, appearance: Appearance): string {
  const scan = blankNonMarkup(page);
  const markup = bootstrapMarkup(scan, appearance);
  const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
  if (headOpen) {
    const at = headOpen.index + headOpen[0].length;
    return page.slice(0, at) + markup + page.slice(at);
  }
  const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
  if (htmlOpen) {
    const at = htmlOpen.index + htmlOpen[0].length;
    return `${page.slice(0, at)}<head>${markup}</head>${page.slice(at)}`;
  }
  const doctype = /^\s*<!doctype[^>]*>/i.exec(page);
  if (doctype) {
    const at = doctype[0].length;
    return `${page.slice(0, at)}<head>${markup}</head>${page.slice(at)}`;
  }
  return `<!doctype html><head>${markup}</head>${page}`;
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.2latestNov 21, 2026>=2 <4349.5 KB1 permissionListed
0.2.1Oct 25, 2026>=2 <4349.2 KB1 permissionListed
0.2.0Oct 23, 2026>=2 <4349.3 KB1 permissionListed

Reviews and comments

0 threads · 0 reviews

No comments yet.