1 import * as MarkdownIt from 'markdown-it'
2 import { Injectable } from '@angular/core'
3 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
7 ENHANCED_WITH_HTML_RULES,
10 } from '@shared/core-utils/renderer/markdown'
11 import { HtmlRendererService } from './html-renderer.service'
13 type MarkdownParsers = {
14 textMarkdownIt: MarkdownIt
15 textWithHTMLMarkdownIt: MarkdownIt
17 enhancedMarkdownIt: MarkdownIt
18 enhancedWithHTMLMarkdownIt: MarkdownIt
20 unsafeMarkdownIt: MarkdownIt
22 customPageMarkdownIt: MarkdownIt
25 type MarkdownConfig = {
32 type MarkdownParserConfigs = {
33 [id in keyof MarkdownParsers]: MarkdownConfig
37 export class MarkdownService {
38 private markdownParsers: MarkdownParsers = {
40 textWithHTMLMarkdownIt: null,
42 enhancedMarkdownIt: null,
43 enhancedWithHTMLMarkdownIt: null,
45 unsafeMarkdownIt: null,
47 customPageMarkdownIt: null
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 },
53 enhancedMarkdownIt: { rules: ENHANCED_RULES, breaks: true, html: false },
54 enhancedWithHTMLMarkdownIt: { rules: ENHANCED_WITH_HTML_RULES, breaks: true, html: true, escape: true },
56 unsafeMarkdownIt: { rules: COMPLETE_RULES, breaks: true, html: true, escape: false },
58 customPageMarkdownIt: { rules: COMPLETE_RULES, breaks: false, html: true, escape: true }
61 private emojiModule: any
63 constructor (private htmlRenderer: HtmlRendererService) {}
65 textMarkdownToHTML (options: {
67 withHtml?: boolean // default false
68 withEmoji?: boolean // default false
70 const { markdown, withHtml = false, withEmoji = false } = options
72 if (withHtml) return this.render({ name: 'textWithHTMLMarkdownIt', markdown, withEmoji })
74 return this.render({ name: 'textMarkdownIt', markdown, withEmoji })
77 enhancedMarkdownToHTML (options: {
79 withHtml?: boolean // default false
80 withEmoji?: boolean // default false
82 const { markdown, withHtml = false, withEmoji = false } = options
84 if (withHtml) return this.render({ name: 'enhancedWithHTMLMarkdownIt', markdown, withEmoji })
86 return this.render({ name: 'enhancedMarkdownIt', markdown, withEmoji })
89 markdownToUnsafeHTML (options: { markdown: string }) {
90 return this.render({ name: 'unsafeMarkdownIt', markdown: options.markdown, withEmoji: true })
93 customPageMarkdownToHTML (options: {
95 additionalAllowedTags: string[]
97 const { markdown, additionalAllowedTags } = options
99 return this.render({ name: 'customPageMarkdownIt', markdown, withEmoji: true, additionalAllowedTags })
102 // ---------------------------------------------------------------------------
104 processVideoTimestamps (videoShortUUID: string, html: string) {
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))
108 const url = decorateVideoLink({
109 url: buildVideoLink({ shortUUID: videoShortUUID }),
113 // Sync class name with timestamp-route-transformer directive
114 return `<a class="video-timestamp" href="${url}">${str}</a>`
118 private async render (options: {
119 name: keyof MarkdownParsers
122 additionalAllowedTags?: string[]
124 const { name, markdown, withEmoji, additionalAllowedTags } = options
125 if (!markdown) return ''
127 const config = this.parsersConfig[name]
128 if (!this.markdownParsers[name]) {
129 this.markdownParsers[name] = await this.createMarkdownIt(config)
132 if (!this.emojiModule) {
133 this.emojiModule = (await import('markdown-it-emoji/light')).default
136 this.markdownParsers[name].use(this.emojiModule)
140 let html = this.markdownParsers[name].render(markdown)
141 html = this.avoidTruncatedTags(html)
143 if (config.escape) return this.htmlRenderer.toSafeHtml(html, additionalAllowedTags)
148 private async createMarkdownIt (config: MarkdownConfig) {
149 // FIXME: import('...') returns a struct module, containing a "default" field
150 const MarkdownItClass: typeof import ('markdown-it') = (await import('markdown-it') as any).default
152 const markdownIt = new MarkdownItClass('zero', { linkify: true, breaks: config.breaks, html: config.html })
154 for (const rule of config.rules) {
155 markdownIt.enable(rule)
158 this.setTargetToLinks(markdownIt)
163 private setTargetToLinks (markdownIt: MarkdownIt) {
164 // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
165 const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) {
166 return self.renderToken(tokens, idx, options)
169 markdownIt.renderer.rules.link_open = function (tokens, index, options, env, self) {
170 const token = tokens[index]
172 const targetIndex = token.attrIndex('target')
173 if (targetIndex < 0) token.attrPush([ 'target', '_blank' ])
174 else token.attrs[targetIndex][1] = '_blank'
176 const relIndex = token.attrIndex('rel')
177 if (relIndex < 0) token.attrPush([ 'rel', 'noopener noreferrer' ])
178 else token.attrs[relIndex][1] = 'noopener noreferrer'
180 // pass token to default renderer.*
181 return defaultRender(tokens, index, options, env, self)
185 private avoidTruncatedTags (html: string) {
186 return html.replace(/\*\*?([^*]+)$/, '$1')
187 .replace(/<a[^>]+>([^<]+)<\/a>\s*...((<\/p>)|(<\/li>)|(<\/strong>))?$/mi, '$1...')
188 .replace(/\[[^\]]+\]\(([^)]+)$/m, '$1')
189 .replace(/\s?\[[^\]]+\]?[.]{3}<\/p>$/m, '...</p>')