Slightly more robust syntax highlighting

This commit is contained in:
oobabooga 2025-09-17 21:57:17 -07:00
parent dd6d2223a5
commit e4412f0634

View file

@ -249,44 +249,48 @@ function doSyntaxHighlighting() {
if (messageBodies.length > 0) { if (messageBodies.length > 0) {
observer.disconnect(); observer.disconnect();
let hasSeenVisible = false; try {
let hasSeenVisible = false;
// Go from last message to first // Go from last message to first
for (let i = messageBodies.length - 1; i >= 0; i--) { for (let i = messageBodies.length - 1; i >= 0; i--) {
const messageBody = messageBodies[i]; const messageBody = messageBodies[i];
if (isElementVisibleOnScreen(messageBody)) { if (isElementVisibleOnScreen(messageBody)) {
hasSeenVisible = true; hasSeenVisible = true;
// Handle both code and math in a single pass through each message // Handle both code and math in a single pass through each message
const codeBlocks = messageBody.querySelectorAll("pre code:not([data-highlighted])"); const codeBlocks = messageBody.querySelectorAll("pre code:not([data-highlighted])");
codeBlocks.forEach((codeBlock) => { codeBlocks.forEach((codeBlock) => {
hljs.highlightElement(codeBlock); hljs.highlightElement(codeBlock);
codeBlock.setAttribute("data-highlighted", "true"); codeBlock.setAttribute("data-highlighted", "true");
codeBlock.classList.add("pretty_scrollbar"); codeBlock.classList.add("pretty_scrollbar");
}); });
// Only render math in visible elements // Only render math in visible elements
const mathContainers = messageBody.querySelectorAll("p, span, li, td, th, h1, h2, h3, h4, h5, h6, blockquote, figcaption, caption, dd, dt"); const mathContainers = messageBody.querySelectorAll("p, span, li, td, th, h1, h2, h3, h4, h5, h6, blockquote, figcaption, caption, dd, dt");
mathContainers.forEach(container => { mathContainers.forEach(container => {
if (isElementVisibleOnScreen(container)) { if (isElementVisibleOnScreen(container)) {
renderMathInElement(container, { renderMathInElement(container, {
delimiters: [ delimiters: [
{ left: "$$", right: "$$", display: true }, { left: "$$", right: "$$", display: true },
{ left: "\\(", right: "\\)", display: false }, { left: "\\(", right: "\\)", display: false },
{ left: "\\[", right: "\\]", display: true }, { left: "\\[", right: "\\]", display: true },
], ],
}); });
} }
}); });
} else if (hasSeenVisible) { } else if (hasSeenVisible) {
// We've seen visible messages but this one is not visible // We've seen visible messages but this one is not visible
// Since we're going from last to first, we can break // Since we're going from last to first, we can break
break; break;
}
} }
}
observer.observe(targetElement, config); } finally {
observer.observe(targetElement, config);
}
} }
} }