/**
* Code snapshot rendering & export utilities (CodeSnap-style).
*
* Flow: selected code text -> shiki re-render (reusing the AI highlighter
* singleton) -> CodeSnap-like shell DOM (traffic lights / title / line
* numbers / background) -> PNG export either to the system clipboard
* (Tauri `writeImage`) or to a file (dialog + fs, with a browser-download
* fallback for web mode).
*
* The rendered snapshot DOM is fully self-contained: it embeds its own
* `` +
`
`
);
}
/** Convert a snapshot DOM element into a PNG data URL. */
export async function snapshotElementToPng(element: HTMLElement): Promise {
const domtoimage = (await import("dom-to-image-more")).default;
// 预览区允许滚动,因此导出尺寸必须覆盖完整内容,而不是只取当前可见宽度。
const width = Math.max(element.offsetWidth, element.scrollWidth);
const height = Math.max(element.offsetHeight, element.scrollHeight);
const basePixels = width * height;
if (width > MAX_EXPORT_CANVAS_EDGE || height > MAX_EXPORT_CANVAS_EDGE || basePixels > MAX_EXPORT_CANVAS_PIXELS) {
throw new Error(`Snapshot is too large to export safely (${width} × ${height}px). Reduce the code size and try again.`);
}
const targetScale = Math.min(MAX_EXPORT_PIXEL_RATIO, Math.max(1, typeof window === "undefined" ? 1 : window.devicePixelRatio || 1));
const scale = Math.min(targetScale, MAX_EXPORT_CANVAS_EDGE / width, MAX_EXPORT_CANVAS_EDGE / height, Math.sqrt(MAX_EXPORT_CANVAS_PIXELS / basePixels));
const useLegacyLineNumberFallback = legacyWebViewExportFallbackEnabled();
return domtoimage.toPng(element, {
quality: 1,
width,
height,
// dom-to-image-more 使用 scale 放大实际画布;pixelRatio 不是该库支持的参数。
scale,
adjustPseudoElement: useLegacyLineNumberFallback
? (node: Node, pseudoElement: ":before" | ":after") => {
if (pseudoElement === ":before" && isSnapshotNumberedLineNode(node)) {
return false;
}
return undefined;
}
: undefined,
onclone: useLegacyLineNumberFallback
? (clone: Node) => {
if (typeof (clone as ParentNode).querySelectorAll === "function") {
materializeSnapshotCloneLineNumbers(clone as ParentNode);
}
}
: undefined,
style: {
width: `${width}px`,
height: `${height}px`,
},
});
}
async function dataUrlToBlob(dataUrl: string): Promise {
return await (await fetch(dataUrl)).blob();
}
/**
* Copy a PNG data URL to the system clipboard. Uses the Tauri
* clipboard-manager `writeImage` on desktop and falls back to the Web
* Clipboard API (`ClipboardItem`) for web mode.
*/
export async function copyPngDataUrlToClipboard(dataUrl: string): Promise {
const blob = await dataUrlToBlob(dataUrl);
if (isTauriRuntime()) {
const { writeImage } = await import("@tauri-apps/plugin-clipboard-manager");
await writeImage(new Uint8Array(await blob.arrayBuffer()));
return;
}
if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
return;
}
throw new Error("Clipboard image write is not supported in this environment");
}
/**
* Save a PNG data URL to a file. On desktop this opens the native save
* dialog; on web it downloads the image. Returns false when the user
* cancels the native save dialog.
*/
export async function savePngDataUrlToFile(dataUrl: string, defaultName: string): Promise {
const blob = await dataUrlToBlob(dataUrl);
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
const { writeFile } = await import("@tauri-apps/plugin-fs");
const path = await save({
defaultPath: defaultName,
filters: [{ name: "PNG", extensions: ["png"] }],
});
if (!path) return false;
// Native write errors must reach the caller so the UI never claims the
// user-selected path was saved when the filesystem rejected it.
await writeFile(path, new Uint8Array(await blob.arrayBuffer()));
return true;
}
const url = URL.createObjectURL(blob);
try {
const a = document.createElement("a");
a.href = url;
a.download = defaultName;
a.click();
} finally {
URL.revokeObjectURL(url);
}
return true;
}