Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | 14x 14x 14x 14x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 1x 8x 8x 1x 8x 8x 7x 7x 2x 2x 2x 2x 3x 3x 3x 3x 2x 2x 2x 6x 5x 5x 5x 5x 3x 1x 1x 1x 1x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 8x 4x 2x 2x 2x 4x 4x 4x 2x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 4x 4x 4x 4x 1x 1x | import { mermaidConfig } from "./mermaidConfig";
import { lightTileSrc } from "@/components/map/tiles";
// ─── PDF export ───────────────────────────────────────────────────────────────
//
// Saves a rendered chat response as a PDF by printing the *live DOM* through a
// hidden iframe, from which every browser's print dialog offers "Save as PDF".
//
// Printing the DOM rather than re-deriving a document from the markdown is what
// makes diagrams and graphs come out right: Mermaid diagrams, Recharts charts,
// the network graph and KaTeX math are already SVG on screen, and SVG prints as
// vector — sharp at any zoom, and no rasteriser that has to understand the
// stylesheet. (A canvas-based snapshot library would also choke on Tailwind v4's
// `oklch()` colours, which it cannot parse.)
//
// Two things are deliberately re-derived for print:
// · `<canvas>` elements, which do not survive cloning, are swapped for a PNG
// snapshot taken from the live element;
// · Mermaid diagrams, which bake their theme into the rendered SVG, are
// re-rendered light so a diagram authored in dark mode is still legible on
// white paper.
//
// The print document deliberately carries no `dark` class, so every `dark:`
// variant (`&:is(.dark *)`) drops out and the page prints light.
/** Elements that are chrome rather than content, and must not print.
*
* A map's attribution control is deliberately *not* chrome: OpenStreetMap and
* CARTO require the credit to travel with the tiles, and an exported PDF is a
* document that leaves the platform. Only the interactive controls go.
*/
const HIDE_SELECTOR = [
"[data-pdf-hide]",
"button",
".leaflet-control-container .leaflet-control:not(.leaflet-control-attribution)",
].join(",");
/** Give up waiting on stylesheets, images and fonts after this long. */
const ASSET_TIMEOUT_MS = 5000;
/** How long to leave the iframe mounted when `afterprint` never fires. */
const TEARDOWN_MS = 60_000;
const PRINT_CSS = `
@page { size: A4; margin: 16mm 14mm; }
html, body {
background: #ffffff;
margin: 0;
padding: 0;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.pdf-page { color: #111827; }
.pdf-header {
border-bottom: 1px solid #e5e7eb;
padding-bottom: 10px;
margin-bottom: 18px;
}
.pdf-title { font: 600 15px/1.3 system-ui, sans-serif; margin: 0; color: #111827; }
.pdf-subtitle { font: 400 11px/1.4 system-ui, sans-serif; margin: 4px 0 0; color: #6b7280; }
.pdf-body { break-inside: auto; }
.pdf-footer {
border-top: 1px solid #e5e7eb;
margin-top: 18px;
padding-top: 8px;
font: 400 10px/1.4 system-ui, sans-serif;
color: #6b7280;
}
/* On screen the thread and its wide blocks scroll inside a fixed box; on
paper nothing scrolls, so a clipped box would silently lose content. */
.pdf-body, .pdf-body * { max-height: none !important; overflow: visible !important; }
.recharts-responsive-container, .recharts-wrapper { max-width: 100% !important; }
/* …except a map, whose tiles are laid out beyond its edges and clipped by it. */
.pdf-body .leaflet-container { overflow: hidden !important; }
/* The on-screen bubble is a card; on paper the page is the card. */
.pdf-body > * { border: 0 !important; border-radius: 0 !important; padding: 0 !important; background: transparent !important; }
* { box-shadow: none !important; }
img, svg { max-width: 100%; }
pre, table, svg, figure, blockquote, .not-prose {
break-inside: avoid;
page-break-inside: avoid;
}
h1, h2, h3, h4 { break-after: avoid; page-break-after: avoid; }
`;
export interface PdfExportOptions {
/** Rendered node to print — normally the response bubble. */
node: HTMLElement;
/** Document title; browsers seed the save dialog's filename from it. */
title: string;
/** Optional line under the title, e.g. the model and when it answered. */
subtitle?: string;
/** Optional line closing the page, e.g. the AI disclosure. */
footer?: string;
/**
* Seam for tests: how the prepared frame is sent to the printer. jsdom has
* no `window.print`, so the default is swapped out rather than stubbed.
*/
printer?: (win: Window) => void;
}
/** Replace every `<canvas>` in the clone with a PNG of the live one.
*
* Must run before {@link sanitiseForPrint}, which changes the clone's element
* order relative to the source it is indexed against.
*/
export function inlineCanvases(source: HTMLElement, clone: HTMLElement): void {
const live = source.querySelectorAll("canvas");
const copies = clone.querySelectorAll("canvas");
live.forEach((canvas, i) => {
const target = copies[i];
Iif (!target) return;
try {
const img = clone.ownerDocument.createElement("img");
img.src = canvas.toDataURL("image/png");
img.style.width = `${canvas.clientWidth || canvas.width}px`;
target.replaceWith(img);
} catch {
// Tainted or unsupported canvas — drop it rather than print a blank box.
target.remove();
}
});
}
/** Strip interactive chrome and reveal hover-only content in a print clone. */
export function sanitiseForPrint(clone: HTMLElement): HTMLElement {
clone.querySelectorAll(HIDE_SELECTOR).forEach((el) => el.remove());
// Affordances that only appear on hover would otherwise print invisible.
clone
.querySelectorAll<HTMLElement>(".opacity-0")
.forEach((el) => el.classList.remove("opacity-0"));
clone.removeAttribute("style");
return clone;
}
/** Re-render Mermaid diagrams in the light theme.
*
* Mermaid bakes its theme into the SVG it emits, so a diagram rendered while
* the app was in dark mode is light-on-transparent — invisible on paper. The
* source is carried on the rendered block as `data-mermaid-source`.
*
* Mermaid's config is global, so the app's own theme is restored afterwards.
*/
export async function relightMermaid(clone: HTMLElement): Promise<void> {
const blocks = Array.from(
clone.querySelectorAll<HTMLElement>("[data-mermaid-source]"),
);
if (blocks.length === 0) return;
const mermaid = (await import("mermaid")).default;
mermaid.initialize(mermaidConfig("default"));
const stamp = Date.now();
await Promise.all(
blocks.map(async (block, i) => {
const source = block.dataset.mermaidSource ?? "";
Iif (!source) return;
try {
const { svg } = await mermaid.render(`pdfmermaid${stamp}x${i}`, source);
block.innerHTML = svg;
} catch {
// Keep whatever was on screen rather than losing the diagram entirely.
}
}),
);
// Restore the app's theme so the next on-screen render is unaffected.
const dark = clone.ownerDocument.documentElement.classList.contains("dark");
mermaid.initialize(mermaidConfig(dark ? "dark" : "default"));
}
/** Swap a dark-mode map's tiles for the light basemap.
*
* Tiles are `<img>`, so they clone and print as they are — but a dark basemap
* on a light page is ink-heavy and out of step with the rest of the document.
* Both styles come from the same tile server, so this is a URL swap that
* keeps the basemap key (components/map/tiles.ts); the exporter then waits
* for the new tiles like any other image.
*/
export function relightMapTiles(clone: HTMLElement): void {
clone
.querySelectorAll<HTMLImageElement>("img.leaflet-tile")
.forEach((tile) => {
const src = tile.getAttribute("src") ?? "";
const light = lightTileSrc(src);
if (light !== src) tile.setAttribute("src", light);
});
}
/** Copy the app's stylesheets into the print document.
*
* `<link>` hrefs are re-read from the resolved `.href` property, because the
* iframe document has no base URL to resolve a relative one against.
*/
export function copyStyles(from: Document, to: Document): void {
from
.querySelectorAll<HTMLStyleElement | HTMLLinkElement>(
'style, link[rel="stylesheet"]',
)
.forEach((node) => {
if (node.tagName === "LINK") {
const link = to.createElement("link");
link.rel = "stylesheet";
link.href = (node as HTMLLinkElement).href;
to.head.appendChild(link);
} else {
const style = to.createElement("style");
style.textContent = node.textContent;
to.head.appendChild(style);
}
});
}
/** Wrap the sanitised clone in a titled page, closed by an optional footer. */
export function buildPage(
doc: Document,
body: HTMLElement,
title: string,
subtitle?: string,
footer?: string,
): HTMLElement {
const page = doc.createElement("div");
page.className = "pdf-page";
const header = doc.createElement("header");
header.className = "pdf-header";
const heading = doc.createElement("p");
heading.className = "pdf-title";
heading.textContent = title;
header.appendChild(heading);
if (subtitle) {
const sub = doc.createElement("p");
sub.className = "pdf-subtitle";
sub.textContent = subtitle;
header.appendChild(sub);
}
const content = doc.createElement("div");
content.className = "pdf-body";
content.appendChild(body);
page.appendChild(header);
page.appendChild(content);
if (footer) {
const foot = doc.createElement("footer");
foot.className = "pdf-footer";
foot.textContent = footer;
page.appendChild(foot);
}
return page;
}
/** Resolve once every stylesheet, image and font is ready, or on timeout. */
async function waitForAssets(doc: Document): Promise<void> {
const settled = (el: HTMLElement) =>
new Promise<void>((resolve) => {
el.addEventListener("load", () => resolve(), { once: true });
el.addEventListener("error", () => resolve(), { once: true });
});
const pending: Promise<unknown>[] = [];
doc
.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')
.forEach((link) => pending.push(settled(link)));
doc.querySelectorAll("img").forEach((img) => {
Eif (!img.complete) pending.push(settled(img));
});
const fonts = (doc as Document & { fonts?: FontFaceSet }).fonts;
Iif (fonts?.ready) pending.push(fonts.ready);
if (pending.length === 0) return;
await Promise.race([
Promise.all(pending),
new Promise<void>((resolve) => setTimeout(resolve, ASSET_TIMEOUT_MS)),
]);
}
/** Print a rendered node as a PDF-ready document.
*
* Resolves once the print dialog has been opened — the save itself is the
* browser's, so there is nothing further to await.
*/
export async function exportNodeToPdf(options: PdfExportOptions): Promise<void> {
const { node, title, subtitle, footer } = options;
const print =
options.printer ??
((win: Window) => {
win.focus();
win.print();
});
const ownerDoc = node.ownerDocument;
const clone = node.cloneNode(true) as HTMLElement;
inlineCanvases(node, clone);
sanitiseForPrint(clone);
relightMapTiles(clone);
await relightMermaid(clone);
const frame = ownerDoc.createElement("iframe");
frame.setAttribute("aria-hidden", "true");
frame.setAttribute("title", title);
frame.style.cssText =
"position:fixed;right:0;bottom:0;width:0;height:0;border:0;opacity:0;";
ownerDoc.body.appendChild(frame);
const doc = frame.contentDocument;
const win = frame.contentWindow;
Iif (!doc || !win) {
frame.remove();
throw new Error("Could not open a print view.");
}
doc.open();
doc.write("<!doctype html><html><head><meta charset='utf-8'></head><body></body></html>");
doc.close();
doc.title = title;
copyStyles(ownerDoc, doc);
const printStyle = doc.createElement("style");
printStyle.textContent = PRINT_CSS;
doc.head.appendChild(printStyle);
doc.body.appendChild(buildPage(doc, clone, title, subtitle, footer));
await waitForAssets(doc);
// Chrome names the saved file after the *top* document, so borrow the title
// for the length of the dialog and hand it back afterwards.
const originalTitle = ownerDoc.title;
ownerDoc.title = title;
let done = false;
const teardown = () => {
Iif (done) return;
done = true;
ownerDoc.title = originalTitle;
frame.remove();
};
win.addEventListener("afterprint", teardown, { once: true });
setTimeout(teardown, TEARDOWN_MS);
try {
print(win);
} catch (err) {
teardown();
throw err;
}
}
|