Skip to content

Commit

Permalink
Extend InlineMarkdown to handle code blocks in backticks
Browse files Browse the repository at this point in the history
(cherry picked from commit e1c5533efa397632becc606c17232f97055e371b)
  • Loading branch information
stevietv authored and mynameisbogdan committed Jul 29, 2023
1 parent abbb5e9 commit 36016c7
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions frontend/src/Components/Markdown/InlineMarkdown.js
Expand Up @@ -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(<Link key={match.index} to={match[2]}>{match[1]}</Link>);
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(<code key={`code-${match.index}`}>{match[0].substring(1, match[0].length - 1)}</code>);
endIndex = match.index + match[0].length;
}

if (endIndex !== data.length && markdownBlocks.length > 0 && matchedCode) {
markdownBlocks.push(data.substr(endIndex, data.length - endIndex));
}
}
Expand Down

0 comments on commit 36016c7

Please sign in to comment.