Skip to content

Commit

Permalink
Merge pull request #1136 from geyserfund/hotfix/add-fallback-for-regex
Browse files Browse the repository at this point in the history
fix: add fallback for regex
  • Loading branch information
sajald77 authored Sep 3, 2023
2 parents b387f4e + 98d4c3f commit 5ae9206
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions src/forms/markdown/helpers/PreviewRenderer.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable prefer-regex-literals */
import { RemirrorRenderer } from '@remirror/react'
import DOMPurify from 'dompurify'
import { getRemirrorJSON, RemirrorContentType, RemirrorManager } from 'remirror'
Expand Down Expand Up @@ -29,13 +30,35 @@ export const PreviewRenderer = ({
)
}

export const matchMarkDownSpecialKeysAtLineEnd =
/(?<!.*(\|\n|\||>))\n(?!.*(\*|_|#|-|\[|>|\n\||\||`|[0-9]+(\.|\))))/g

export const FormatWhiteSpaceForMarkDownString = (value: string): string => {
const adjustForLineChange = value
? value.replaceAll(matchMarkDownSpecialKeysAtLineEnd, '<br />')
: ''
let adjustForLineChange: string

// This replaves \n with <br /> except when the \n is followed by a link, table, header, list, blockquote, code block, or horizontal rule

try {
const requiredRegex = new RegExp(
/(?<!.*(\|\n|\||>))\n(?!.*(\*|_|#|-|\[|>|\n\||\||`|[0-9]+(\.|\))))/g,
)
adjustForLineChange = value ? value.replaceAll(requiredRegex, '<br />') : ''
} catch (e) {
adjustForLineChange = replaceMatchingRegex(value)
}

return DOMPurify.sanitize(adjustForLineChange, { ADD_TAGS: ['iframe'] })
}

const replaceMatchingRegex = (str: string) => {
const lineBreaks = str.split('\n')
const replacedLines = lineBreaks.map((line) => {
if (!line.match(/.*(\|\n|\||>)/)) {
return line.replace(
/(.*)(\n)(.*(\*|_|#|-|\[|>|\n\||\||`|[0-9]+(\.|\))))/g,
'<br />',
)
}

return line
})

return replacedLines.join('\n')
}

0 comments on commit 5ae9206

Please sign in to comment.