]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/renderer/markdown.service.ts
Refactor markdown/sanitize html code
[github/Chocobozzz/PeerTube.git] / client / src / app / core / renderer / markdown.service.ts
CommitLineData
14aa8556 1import * as MarkdownIt from 'markdown-it'
67ed6552
C
2import { buildVideoLink } from 'src/assets/player/utils'
3import { Injectable } from '@angular/core'
9ff36c2d
C
4import {
5 COMPLETE_RULES,
6 ENHANCED_RULES,
7 ENHANCED_WITH_HTML_RULES,
8 TEXT_RULES,
9 TEXT_WITH_HTML_RULES
10} from '@shared/core-utils/renderer/markdown'
67ed6552 11import { HtmlRendererService } from './html-renderer.service'
7e049ea4
C
12
13type MarkdownParsers = {
14 textMarkdownIt: MarkdownIt
3131c13e
C
15 textWithHTMLMarkdownIt: MarkdownIt
16
7e049ea4 17 enhancedMarkdownIt: MarkdownIt
3131c13e
C
18 enhancedWithHTMLMarkdownIt: MarkdownIt
19
7e049ea4
C
20 completeMarkdownIt: MarkdownIt
21}
22
23type MarkdownConfig = {
24 rules: string[]
25 html: boolean
26 escape?: boolean
27}
28
29type MarkdownParserConfigs = {
30 [id in keyof MarkdownParsers]: MarkdownConfig
31}
9d9597df
C
32
33@Injectable()
34export class MarkdownService {
7e049ea4
C
35 private markdownParsers: MarkdownParsers = {
36 textMarkdownIt: null,
3131c13e 37 textWithHTMLMarkdownIt: null,
7e049ea4 38 enhancedMarkdownIt: null,
3131c13e 39 enhancedWithHTMLMarkdownIt: null,
7e049ea4
C
40 completeMarkdownIt: null
41 }
42 private parsersConfig: MarkdownParserConfigs = {
9ff36c2d
C
43 textMarkdownIt: { rules: TEXT_RULES, html: false },
44 textWithHTMLMarkdownIt: { rules: TEXT_WITH_HTML_RULES, html: true, escape: true },
3131c13e 45
9ff36c2d
C
46 enhancedMarkdownIt: { rules: ENHANCED_RULES, html: false },
47 enhancedWithHTMLMarkdownIt: { rules: ENHANCED_WITH_HTML_RULES, html: true, escape: true },
3131c13e 48
9ff36c2d 49 completeMarkdownIt: { rules: COMPLETE_RULES, html: true }
7e049ea4 50 }
621d99f5 51
7e049ea4 52 constructor (private htmlRenderer: HtmlRendererService) {}
9d9597df 53
0672dc76 54 textMarkdownToHTML (markdown: string, withHtml = false, withEmoji = false) {
55 if (withHtml) return this.render('textWithHTMLMarkdownIt', markdown, withEmoji)
3131c13e 56
0672dc76 57 return this.render('textMarkdownIt', markdown, withEmoji)
7e049ea4 58 }
66b16caf 59
0672dc76 60 enhancedMarkdownToHTML (markdown: string, withHtml = false, withEmoji = false) {
61 if (withHtml) return this.render('enhancedWithHTMLMarkdownIt', markdown, withEmoji)
41d71344 62
0672dc76 63 return this.render('enhancedMarkdownIt', markdown, withEmoji)
07fa4c97
C
64 }
65
3131c13e 66 completeMarkdownToHTML (markdown: string) {
0672dc76 67 return this.render('completeMarkdownIt', markdown, true)
7e049ea4
C
68 }
69
b29bf61d
RK
70 async processVideoTimestamps (html: string) {
71 return html.replace(/((\d{1,2}):)?(\d{1,2}):(\d{1,2})/g, function (str, _, h, m, s) {
72 const t = (3600 * +(h || 0)) + (60 * +(m || 0)) + (+(s || 0))
73 const url = buildVideoLink({ startTime: t })
74 return `<a class="video-timestamp" href="${url}">${str}</a>`
75 })
76 }
77
0672dc76 78 private async render (name: keyof MarkdownParsers, markdown: string, withEmoji = false) {
53055a11 79 if (!markdown) return ''
07fa4c97 80
7e049ea4
C
81 const config = this.parsersConfig[ name ]
82 if (!this.markdownParsers[ name ]) {
83 this.markdownParsers[ name ] = await this.createMarkdownIt(config)
0672dc76 84
85 if (withEmoji) {
04c7f701 86 // TODO: write types
87 const emoji = require('markdown-it-emoji/light')
88 this.markdownParsers[ name ].use(emoji)
0672dc76 89 }
41d71344
C
90 }
91
7e049ea4
C
92 let html = this.markdownParsers[ name ].render(markdown)
93 html = this.avoidTruncatedTags(html)
621d99f5 94
7e049ea4 95 if (config.escape) return this.htmlRenderer.toSafeHtml(html)
1eb23e12 96
7e049ea4 97 return html
1eb23e12
C
98 }
99
7e049ea4 100 private async createMarkdownIt (config: MarkdownConfig) {
14aa8556 101 // FIXME: import('...') returns a struct module, containing a "default" field
41d71344
C
102 const MarkdownItClass: typeof import ('markdown-it') = (await import('markdown-it') as any).default
103
7e049ea4 104 const markdownIt = new MarkdownItClass('zero', { linkify: true, breaks: true, html: config.html })
621d99f5 105
7e049ea4 106 for (const rule of config.rules) {
621d99f5
C
107 markdownIt.enable(rule)
108 }
109
110 this.setTargetToLinks(markdownIt)
111
112 return markdownIt
113 }
3d9eaae3 114
41d71344 115 private setTargetToLinks (markdownIt: MarkdownIt) {
9d9597df 116 // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
3d9eaae3 117 const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) {
9d9597df
C
118 return self.renderToken(tokens, idx, options)
119 }
120
632c5e36
C
121 markdownIt.renderer.rules.link_open = function (tokens, index, options, env, self) {
122 const token = tokens[index]
9d9597df 123
632c5e36
C
124 const targetIndex = token.attrIndex('target')
125 if (targetIndex < 0) token.attrPush([ 'target', '_blank' ])
126 else token.attrs[targetIndex][1] = '_blank'
127
128 const relIndex = token.attrIndex('rel')
129 if (relIndex < 0) token.attrPush([ 'rel', 'noopener noreferrer' ])
130 else token.attrs[relIndex][1] = 'noopener noreferrer'
9d9597df
C
131
132 // pass token to default renderer.
632c5e36 133 return defaultRender(tokens, index, options, env, self)
9d9597df
C
134 }
135 }
07fa4c97 136
8eaa6d62 137 private avoidTruncatedTags (html: string) {
e182430a
C
138 return html.replace(/\*\*?([^*]+)$/, '$1')
139 .replace(/<a[^>]+>([^<]+)<\/a>\s*...((<\/p>)|(<\/li>)|(<\/strong>))?$/mi, '$1...')
b29bf61d 140 .replace(/\[[^\]]+\]\(([^\)]+)$/m, '$1')
f5b72c39 141 .replace(/\s?\[[^\]]+\]?[.]{3}<\/p>$/m, '...</p>')
07fa4c97 142 }
9d9597df 143}