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