Formatting output using markdown-it and MathJax

This commit is contained in:
Joakim Persson
2024-07-30 14:32:00 +02:00
parent b4a35bafef
commit ecf2ddf46e
+30 -13
View File
@@ -3,15 +3,11 @@
const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');
// // Check for Marked
// if (typeof marked === 'undefined') {
// console.log('Marked is not defined');
// const script = document.createElement('script');
// script.src = "https://cdn.jsdelivr.net/npm/marked/marked.min.js";
// script.onload = initializeChatbot;
// document.body.appendChild(script);
// console.log('Marked is now defined');
// }
const parser = window.markdownit();
// const html = markdownIt.use({
// // You can customize the parser options here, e.g., enable/disable certain features
// });
// Define a function to send the user's message to the AI
@@ -46,6 +42,20 @@ function sendMessage() {
}
}
function customRenderer(markdownText) {
// Use a regex pattern to match LaTeX code (e.g. $$...$$ or $...$)
const latexPattern = /(?:\$\$|\\\[)(.*?)?(?:\$\$|\\\])/g;
// Replace each occurrence of LaTeX code with an HTML span element
const html = markdownText.replace(latexPattern, (match, p1) => {
return `<span class="latex">${p1}</span>`;
});
// Return the rendered HTML
return html;
}
// Define a function to render a message in the chatbox with a specific class name
function renderMessage(text, className) {
// Create a new div element to hold the message
@@ -58,13 +68,20 @@ function renderMessage(text, className) {
// messageElement.textContent = text;
// Parse Markdown text into HTML and set it as the innerHTML of the element
messageElement.innerHTML = marked.parse(text);
// messageElement.innerHTML = marked.parse(text);
// Use the markdown-it parser
const html = parser.render(text);
messageElement.innerHTML = html;
// Typeset math
MathJax.typesetPromise([messageElement]);
// Append the message element to the chatbox
// Append the message element to the chatbox immediately
chatbox.appendChild(messageElement);
// Typeset math in the message element
MathJax.typesetPromise([messageElement]).then(() => {
// No need to append anything here, it's already appended above
});
}
// Make the button toggle colour when user presses Enter on keyboard