website-htmx-rustelo-code/site/public/js/highlight-utils.js
2026-07-10 03:44:13 +01:00

48 lines
No EOL
1.5 KiB
JavaScript

// Additional highlight.js utilities (auto-init is handled by bundle)
window.highlightCode = function() {
// Find all code blocks that haven't been highlighted yet
document.querySelectorAll('pre code:not(.hljs)').forEach(function(block) {
if (typeof hljs !== 'undefined' && hljs.highlightElement) {
hljs.highlightElement(block);
}
});
};
window.highlightContainer = function(containerSelector) {
// Highlight code blocks within a specific container
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)
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) {
// Check if any added nodes contain code blocks
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1 && (node.tagName === 'PRE' || node.querySelector('pre'))) {
shouldHighlight = true;
}
});
}
});
if (shouldHighlight) {
setTimeout(function() {
window.highlightCode();
}, 100);
}
});
// Start observing document changes
observer.observe(document.body, {
childList: true,
subtree: true
});
});