From 3ab95fea1dbf3cace0454a3dadd9b317ae231bf6 Mon Sep 17 00:00:00 2001 From: Godfrain Jacques Date: Fri, 14 Jun 2024 18:08:57 -0700 Subject: [PATCH] fix: Improve code snippets display in chats --- .../statusMessage/StatusTextMessage.qml | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/ui/StatusQ/src/StatusQ/Components/private/statusMessage/StatusTextMessage.qml b/ui/StatusQ/src/StatusQ/Components/private/statusMessage/StatusTextMessage.qml index ad49583e49..4dd8a649f1 100644 --- a/ui/StatusQ/src/StatusQ/Components/private/statusMessage/StatusTextMessage.qml +++ b/ui/StatusQ/src/StatusQ/Components/private/statusMessage/StatusTextMessage.qml @@ -69,6 +69,43 @@ Item { return Utils.getMessageWithStyle(formattedMessage) } + + function highlightCodeBlocks(text) { + var codeBlockPattern = /```([^`]+)```/g; + + text = text.replace(/([\s\S]+?)<\/code>/g, function(match, codeBlock) { + return '```' + codeBlock + '```'; + }); + + var highlightedText = text.replace(codeBlockPattern, function(match, codeBlock) { + var codeBlock = addLineSpaces(codeBlock) + return "
" +
+                    highlightSyntax(codeBlock) + "
"; + }); + return highlightedText.replace(/\n/g, "
"); + } + + function addLineSpaces(code) { + return code.split("\n") + .map((line, index) => index === 0 ? `\n ${line}` : ` ${line}`) + .join("\n"); + } + + function highlightSyntax(code) { + var keywords = "\\b(abstract|arguments|await|boolean|break|byte|case|catch|char|class|const|continue|" + + "debugger|default|delete|do|double|else|enum|eval|export|extends|false|final|finally|float|" + + "for|function|goto|if|implements|import|in|instanceof|int|interface|let|long|native|new|null|" + + "package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|" + + "throws|transient|true|try|typeof|var|void|volatile|while|with|yield|" + + "uint32_t|uint64_t|void|char|float|double|bool|long|short|int|" + + "signed|unsigned|const|volatile|static|inline|extern|mutable|class|struct|namespace|using|public|private|protected|virtual|template|typename|new|delete|sizeof|define)\\b"; + var strings = /'[^']*'|"[^"]*"|`[^`]*`/g; + + code = code.replace(strings, '$&'); + code = code.replace(new RegExp(keywords, 'g'), '$1'); + + return code; + } } Rectangle { @@ -92,7 +129,7 @@ Item { anchors.leftMargin: d.isQuote ? 8 : 0 anchors.right: parent.right opacity: !showMoreOpacityMask.active && !horizontalOpacityMask.active ? 1 : 0 - text: d.text + text: d.highlightCodeBlocks(d.text) selectedTextColor: Theme.palette.directColor1 selectionColor: Theme.palette.primaryColor3 color: d.isQuote ? Theme.palette.baseColor1 : Theme.palette.directColor1