From 5aee804bc0ebe7448d72eed261025e7efe9ae52f Mon Sep 17 00:00:00 2001 From: Stevie Robinson Date: Sat, 29 Jul 2023 03:36:06 +0200 Subject: [PATCH] Extend InlineMarkdown to handle code blocks in backticks (cherry picked from commit e1c5533efa397632becc606c17232f97055e371b) --- .../src/Components/Markdown/InlineMarkdown.js | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/frontend/src/Components/Markdown/InlineMarkdown.js b/frontend/src/Components/Markdown/InlineMarkdown.js index dc9ea9bf3..a9f04dc0e 100644 --- a/frontend/src/Components/Markdown/InlineMarkdown.js +++ b/frontend/src/Components/Markdown/InlineMarkdown.js @@ -13,22 +13,45 @@ class InlineMarkdown extends Component { data } = this.props; - // For now only replace links + // For now only replace links or code blocks (not both) const markdownBlocks = []; if (data) { - const regex = RegExp(/\[(.+?)\]\((.+?)\)/g); + const linkRegex = RegExp(/\[(.+?)\]\((.+?)\)/g); let endIndex = 0; let match = null; - while ((match = regex.exec(data)) !== null) { + + while ((match = linkRegex.exec(data)) !== null) { if (match.index > endIndex) { markdownBlocks.push(data.substr(endIndex, match.index - endIndex)); } + markdownBlocks.push({match[1]}); endIndex = match.index + match[0].length; } - if (endIndex !== data.length) { + if (endIndex !== data.length && markdownBlocks.length > 0) { + markdownBlocks.push(data.substr(endIndex, data.length - endIndex)); + } + + const codeRegex = RegExp(/(?=`)`(?!`)[^`]*(?=`)`(?!`)/g); + + endIndex = 0; + match = null; + let matchedCode = false; + + while ((match = codeRegex.exec(data)) !== null) { + matchedCode = true; + + if (match.index > endIndex) { + markdownBlocks.push(data.substr(endIndex, match.index - endIndex)); + } + + markdownBlocks.push({match[0].substring(1, match[0].length - 1)}); + endIndex = match.index + match[0].length; + } + + if (endIndex !== data.length && markdownBlocks.length > 0 && matchedCode) { markdownBlocks.push(data.substr(endIndex, data.length - endIndex)); } }