From 64a2ea007e93b039d59d803d1d7190be9bd254f9 Mon Sep 17 00:00:00 2001 From: Emmy D'Anello Date: Tue, 30 Apr 2024 20:08:56 +0200 Subject: [PATCH] Add basic Markdown rules for the chat Signed-off-by: Emmy D'Anello --- chat/static/chat.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/chat/static/chat.js b/chat/static/chat.js index 89ab947..c4442c8 100644 --- a/chat/static/chat.js +++ b/chat/static/chat.js @@ -157,7 +157,6 @@ function fetchPreviousMessages() { } function receiveFetchedMessages(data) { - console.log(data) let channel_id = data['channel_id'] let new_messages = data['messages'] @@ -237,7 +236,7 @@ function redrawMessages() { messageContentDiv.setAttribute('data-message-id', message['id']) lastContentDiv.appendChild(messageContentDiv) let messageContentSpan = document.createElement('span') - messageContentSpan.innerText = message['content'] + messageContentSpan.innerHTML = markdownToHTML(message['content']) messageContentDiv.appendChild(messageContentSpan) registerMessageContextMenu(message, messageContentDiv, messageContentSpan) @@ -272,7 +271,7 @@ function redrawMessages() { messageContentDiv.setAttribute('data-message-id', message['id']) contentDiv.appendChild(messageContentDiv) let messageContentSpan = document.createElement('span') - messageContentSpan.innerText = message['content'] + messageContentSpan.innerHTML = markdownToHTML(message['content']) messageContentDiv.appendChild(messageContentSpan) registerMessageContextMenu(message, messageContentDiv, messageContentSpan) @@ -290,6 +289,26 @@ function redrawMessages() { messageList.dispatchEvent(new CustomEvent('updatemessages')) } +function markdownToHTML(text) { + let safeText = text.replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'") + let lines = safeText.split('\n') + let htmlLines = [] + for (let line of lines) { + let htmlLine = line + .replaceAll(/_(.*)_/gim, '$1') // Underline + .replaceAll(/\*\*(.*)\*\*/gim, '$1') // Bold + .replaceAll(/\*(.*)\*/gim, '$1') // Italic + .replaceAll(/`(.*)`/gim, '
$1
') // Code + .replaceAll(/(https?:\/\/\S+)/g, '$1') // Links + htmlLines.push(htmlLine) + } + return htmlLines.join('
') +} + function removeAllPopovers() { for (let popover of document.querySelectorAll('*[aria-describedby*="popover"]')) { let instance = bootstrap.Popover.getInstance(popover)