]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/markdown.ts
Fix live update error
[github/Chocobozzz/PeerTube.git] / server / helpers / markdown.ts
CommitLineData
c68e2b2d 1import { getDefaultSanitizeOptions, getTextOnlySanitizeOptions, TEXT_WITH_HTML_RULES } from '@shared/core-utils'
2539932e 2
c68e2b2d
C
3const defaultSanitizeOptions = getDefaultSanitizeOptions()
4const textOnlySanitizeOptions = getTextOnlySanitizeOptions()
84bced65
RK
5
6const sanitizeHtml = require('sanitize-html')
7const markdownItEmoji = require('markdown-it-emoji/light')
8const MarkdownItClass = require('markdown-it')
84bced65 9
c68e2b2d
C
10const markdownItWithHTML = new MarkdownItClass('default', { linkify: true, breaks: true, html: true })
11const markdownItWithoutHTML = new MarkdownItClass('default', { linkify: true, breaks: true, html: false })
84bced65 12
228d8e8e 13const toSafeHtml = (text: string) => {
46460547
C
14 if (!text) return ''
15
84bced65
RK
16 // Restore line feed
17 const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')
18
19 // Convert possible markdown (emojis, emphasis and lists) to html
c68e2b2d
C
20 const html = markdownItWithHTML.enable(TEXT_WITH_HTML_RULES)
21 .use(markdownItEmoji)
22 .render(textWithLineFeed)
84bced65
RK
23
24 // Convert to safe Html
c68e2b2d 25 return sanitizeHtml(html, defaultSanitizeOptions)
84bced65
RK
26}
27
c68e2b2d 28const mdToOneLinePlainText = (text: string) => {
46460547
C
29 if (!text) return ''
30
c68e2b2d
C
31 markdownItWithoutHTML.use(markdownItEmoji)
32 .use(plainTextPlugin)
33 .render(text)
a073c912
RK
34
35 // Convert to safe Html
c68e2b2d 36 return sanitizeHtml(markdownItWithoutHTML.plainText, textOnlySanitizeOptions)
a073c912
RK
37}
38
84bced65
RK
39// ---------------------------------------------------------------------------
40
41export {
a073c912 42 toSafeHtml,
c68e2b2d
C
43 mdToOneLinePlainText
44}
45
46// ---------------------------------------------------------------------------
47
48// Thanks: https://github.com/wavesheep/markdown-it-plain-text
49function plainTextPlugin (markdownIt: any) {
50 let lastSeparator = ''
51
52 function plainTextRule (state: any) {
53 const text = scan(state.tokens)
54
55 markdownIt.plainText = text.replace(/\s+/g, ' ')
56 }
57
58 function scan (tokens: any[]) {
59 let text = ''
60
61 for (const token of tokens) {
62 if (token.children !== null) {
63 text += scan(token.children)
64 continue
65 }
66
67 if (token.type === 'list_item_close') {
68 lastSeparator = ', '
69 } else if (/[a-zA-Z]+_close/.test(token.type)) {
70 lastSeparator = ' '
71 } else if (token.content) {
72 text += lastSeparator
73 text += token.content
74 }
75 }
76
77 return text
78 }
79
80 markdownIt.core.ruler.push('plainText', plainTextRule)
84bced65 81}