]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/renderer/markdown.service.ts
Merge branch 'release/4.2.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / core / renderer / markdown.service.ts
1 import * as MarkdownIt from 'markdown-it'
2 import { Injectable } from '@angular/core'
3 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
4 import {
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'
11 import { HtmlRendererService } from './html-renderer.service'
12
13 type MarkdownParsers = {
14 textMarkdownIt: MarkdownIt
15 textWithHTMLMarkdownIt: MarkdownIt
16
17 enhancedMarkdownIt: MarkdownIt
18 enhancedWithHTMLMarkdownIt: MarkdownIt
19
20 unsafeMarkdownIt: MarkdownIt
21
22 customPageMarkdownIt: MarkdownIt
23 }
24
25 type MarkdownConfig = {
26 rules: string[]
27 html: boolean
28 breaks: boolean
29 escape?: boolean
30 }
31
32 type MarkdownParserConfigs = {
33 [id in keyof MarkdownParsers]: MarkdownConfig
34 }
35
36 @Injectable()
37 export class MarkdownService {
38 private markdownParsers: MarkdownParsers = {
39 textMarkdownIt: null,
40 textWithHTMLMarkdownIt: null,
41
42 enhancedMarkdownIt: null,
43 enhancedWithHTMLMarkdownIt: null,
44
45 unsafeMarkdownIt: null,
46
47 customPageMarkdownIt: null
48 }
49 private parsersConfig: MarkdownParserConfigs = {
50 textMarkdownIt: { rules: TEXT_RULES, breaks: true, html: false },
51 textWithHTMLMarkdownIt: { rules: TEXT_WITH_HTML_RULES, breaks: true, html: true, escape: true },
52
53 enhancedMarkdownIt: { rules: ENHANCED_RULES, breaks: true, html: false },
54 enhancedWithHTMLMarkdownIt: { rules: ENHANCED_WITH_HTML_RULES, breaks: true, html: true, escape: true },
55
56 unsafeMarkdownIt: { rules: COMPLETE_RULES, breaks: true, html: true, escape: false },
57
58 customPageMarkdownIt: { rules: COMPLETE_RULES, breaks: false, html: true, escape: true }
59 }
60
61 private emojiModule: any
62
63 constructor (private htmlRenderer: HtmlRendererService) {}
64
65 textMarkdownToHTML (markdown: string, withHtml = false, withEmoji = false) {
66 if (withHtml) return this.render({ name: 'textWithHTMLMarkdownIt', markdown, withEmoji })
67
68 return this.render({ name: 'textMarkdownIt', markdown, withEmoji })
69 }
70
71 enhancedMarkdownToHTML (markdown: string, withHtml = false, withEmoji = false) {
72 if (withHtml) return this.render({ name: 'enhancedWithHTMLMarkdownIt', markdown, withEmoji })
73
74 return this.render({ name: 'enhancedMarkdownIt', markdown, withEmoji })
75 }
76
77 unsafeMarkdownToHTML (markdown: string, _trustedInput: true) {
78 return this.render({ name: 'unsafeMarkdownIt', markdown, withEmoji: true })
79 }
80
81 customPageMarkdownToHTML (markdown: string, additionalAllowedTags: string[]) {
82 return this.render({ name: 'customPageMarkdownIt', markdown, withEmoji: true, additionalAllowedTags })
83 }
84
85 processVideoTimestamps (videoShortUUID: string, html: string) {
86 return html.replace(/((\d{1,2}):)?(\d{1,2}):(\d{1,2})/g, function (str, _, h, m, s) {
87 const t = (3600 * +(h || 0)) + (60 * +(m || 0)) + (+(s || 0))
88
89 const url = decorateVideoLink({
90 url: buildVideoLink({ shortUUID: videoShortUUID }),
91 startTime: t
92 })
93
94 // Sync class name with timestamp-route-transformer directive
95 return `<a class="video-timestamp" href="${url}">${str}</a>`
96 })
97 }
98
99 private async render (options: {
100 name: keyof MarkdownParsers
101 markdown: string
102 withEmoji: boolean
103 additionalAllowedTags?: string[]
104 }) {
105 const { name, markdown, withEmoji, additionalAllowedTags } = options
106 if (!markdown) return ''
107
108 const config = this.parsersConfig[name]
109 if (!this.markdownParsers[name]) {
110 this.markdownParsers[name] = await this.createMarkdownIt(config)
111
112 if (withEmoji) {
113 if (!this.emojiModule) {
114 this.emojiModule = (await import('markdown-it-emoji/light')).default
115 }
116
117 this.markdownParsers[name].use(this.emojiModule)
118 }
119 }
120
121 let html = this.markdownParsers[name].render(markdown)
122 html = this.avoidTruncatedTags(html)
123
124 if (config.escape) return this.htmlRenderer.toSafeHtml(html, additionalAllowedTags)
125
126 return html
127 }
128
129 private async createMarkdownIt (config: MarkdownConfig) {
130 // FIXME: import('...') returns a struct module, containing a "default" field
131 const MarkdownItClass: typeof import ('markdown-it') = (await import('markdown-it') as any).default
132
133 const markdownIt = new MarkdownItClass('zero', { linkify: true, breaks: config.breaks, html: config.html })
134
135 for (const rule of config.rules) {
136 markdownIt.enable(rule)
137 }
138
139 this.setTargetToLinks(markdownIt)
140
141 return markdownIt
142 }
143
144 private setTargetToLinks (markdownIt: MarkdownIt) {
145 // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
146 const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) {
147 return self.renderToken(tokens, idx, options)
148 }
149
150 markdownIt.renderer.rules.link_open = function (tokens, index, options, env, self) {
151 const token = tokens[index]
152
153 const targetIndex = token.attrIndex('target')
154 if (targetIndex < 0) token.attrPush([ 'target', '_blank' ])
155 else token.attrs[targetIndex][1] = '_blank'
156
157 const relIndex = token.attrIndex('rel')
158 if (relIndex < 0) token.attrPush([ 'rel', 'noopener noreferrer' ])
159 else token.attrs[relIndex][1] = 'noopener noreferrer'
160
161 // pass token to default renderer.*
162 return defaultRender(tokens, index, options, env, self)
163 }
164 }
165
166 private avoidTruncatedTags (html: string) {
167 return html.replace(/\*\*?([^*]+)$/, '$1')
168 .replace(/<a[^>]+>([^<]+)<\/a>\s*...((<\/p>)|(<\/li>)|(<\/strong>))?$/mi, '$1...')
169 .replace(/\[[^\]]+\]\(([^)]+)$/m, '$1')
170 .replace(/\s?\[[^\]]+\]?[.]{3}<\/p>$/m, '...</p>')
171 }
172 }