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