]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/shared/markdown.service.ts
Add new name/terms/description config options
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / shared / markdown.service.ts
CommitLineData
9d9597df
C
1import { Injectable } from '@angular/core'
2
3import * as MarkdownIt from 'markdown-it'
4
5@Injectable()
6export class MarkdownService {
7 private markdownIt: MarkdownIt.MarkdownIt
8
9 constructor () {
10 this.markdownIt = new MarkdownIt('zero', { linkify: true })
11 .enable('linkify')
12 .enable('autolink')
13 .enable('emphasis')
14 .enable('link')
15 .enable('newline')
16
66b16caf
C
17 this.setTargetToLinks()
18 }
19
20 markdownToHTML (markdown: string) {
21 const html = this.markdownIt.render(markdown)
22
23 // Avoid linkify truncated links
24 return html.replace(/<a[^>]+>([^<]+)<\/a>\s*...(<\/p>)?$/mi, '$1...')
25 }
26
27 private setTargetToLinks () {
9d9597df
C
28 // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
29 const defaultRender = this.markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) {
30 return self.renderToken(tokens, idx, options)
31 }
32
33 this.markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) {
34 // If you are sure other plugins can't add `target` - drop check below
35 const aIndex = tokens[idx].attrIndex('target')
36
37 if (aIndex < 0) {
38 tokens[idx].attrPush(['target', '_blank']) // add new attribute
39 } else {
40 tokens[idx].attrs[aIndex][1] = '_blank' // replace value of existing attr
41 }
42
43 // pass token to default renderer.
44 return defaultRender(tokens, idx, options, env, self)
45 }
46 }
9d9597df 47}