aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/markdown.ts
blob: 0b8c2fabce82e09689042d9e517cb6e751353826 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { getSanitizeOptions, TEXT_WITH_HTML_RULES } from '@shared/core-utils'

const sanitizeOptions = getSanitizeOptions()

const sanitizeHtml = require('sanitize-html')
const markdownItEmoji = require('markdown-it-emoji/light')
const MarkdownItClass = require('markdown-it')
const markdownIt = new MarkdownItClass('default', { linkify: true, breaks: true, html: true })

markdownIt.enable(TEXT_WITH_HTML_RULES)
markdownIt.use(markdownItEmoji)

const toSafeHtml = (text: string) => {
  if (!text) return ''

  // Restore line feed
  const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')

  // Convert possible markdown (emojis, emphasis and lists) to html
  const html = markdownIt.render(textWithLineFeed)

  // Convert to safe Html
  return sanitizeHtml(html, sanitizeOptions)
}

const mdToPlainText = (text: string) => {
  if (!text) return ''

  // Convert possible markdown (emojis, emphasis and lists) to html
  const html = markdownIt.render(text)

  // Convert to safe Html
  const safeHtml = sanitizeHtml(html, sanitizeOptions)

  return safeHtml.replace(/<[^>]+>/g, '')
                 .replace(/\n$/, '')
                 .replace(/\n/g, ', ')
}

// ---------------------------------------------------------------------------

export {
  toSafeHtml,
  mdToPlainText
}