Project: pygitweb

ed1aee1 import { escapeHtml } from "./dom.js";
/** @type {Record<string, unknown>} */
export const D2H_DEFAULT_CONFIG = {
drawFileList: true,
matching: "lines",
outputFormat: "side-by-side",
synchronisedScroll: true,
highlight: true,
// Keep light scheme classes; dark comes from --pgw-diff-* via prefers-color-scheme.
colorScheme: "light",
};
/**
* Render a unified diff string into ``output`` with Diff2HtmlUI.
* @param {HTMLElement} output
* @param {string} diffStr
* @param {Record<string, unknown>} [config]
* @returns {boolean} true when a non-empty diff was drawn
*/
export function renderUnifiedDiff(output, diffStr, config) {
const text = diffStr || "";
if (!text.trim()) {
return false;
}
if (typeof Diff2HtmlUI === "undefined") {
output.innerHTML =
'<p class="text-danger">Diff renderer failed to load.</p>';
return false;
}
try {
const diff2htmlUi = new Diff2HtmlUI(output, text, {
...D2H_DEFAULT_CONFIG,
...(config || {}),
});
diff2htmlUi.draw();
diff2htmlUi.highlightCode();
return true;
} catch (e) {
const message = e && e.message ? e.message : String(e);
output.innerHTML =
'<p class="text-danger">Failed to render diff: ' +
escapeHtml(message) +
"</p>";
return false;
}
}
/**
* Decode a base64-encoded UTF-8 diff payload.
* @param {string} diffB64
* @returns {string}
*/
export function decodeDiffB64(diffB64) {
const raw = atob(diffB64);
if (!raw) return "";
if (typeof TextDecoder !== "undefined") {
return new TextDecoder("utf-8").decode(
Uint8Array.from(raw, (c) => c.charCodeAt(0)),
);
}
return raw;
}