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