Rustelo/templates/shared/public/scripts/highlight-utils.js
2026-07-18 19:57:03 +01:00

48 lines
1.7 KiB
JavaScript

// highlight.js utilities (auto-init is handled by the bundle). Exposes
// window.highlightCode / window.highlightContainer for dynamic content, and a
// MutationObserver fallback for non-HTMX DOM mutations. Under the htmx-ssr
// profile the RusteloReinit 'highlight' handler covers swaps; this observer
// covers any other dynamic insertion. Provenance: promoted from jpl-website.
window.highlightCode = function() {
document.querySelectorAll('pre code:not(.hljs)').forEach(function(block) {
if (typeof hljs !== 'undefined' && hljs.highlightElement) {
hljs.highlightElement(block);
}
});
};
window.highlightContainer = function(containerSelector) {
const container = document.querySelector(containerSelector);
if (container && typeof hljs !== 'undefined') {
container.querySelectorAll('pre code:not(.hljs)').forEach(function(block) {
hljs.highlightElement(block);
});
}
};
// Re-highlight when content changes (for dynamic content not driven by HTMX).
document.addEventListener('DOMContentLoaded', function() {
const observer = new MutationObserver(function(mutations) {
let shouldHighlight = false;
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1 && (node.tagName === 'PRE' || node.querySelector('pre'))) {
shouldHighlight = true;
}
});
}
});
if (shouldHighlight) {
setTimeout(function() {
window.highlightCode();
}, 100);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});