]>
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 () { | |
10 | this.markdownIt = new MarkdownIt('zero', { linkify: true }) | |
11 | .enable('linkify') | |
12 | .enable('autolink') | |
13 | .enable('emphasis') | |
14 | .enable('link') | |
15 | .enable('newline') | |
16 | ||
17 | // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer | |
18 | const defaultRender = this.markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) { | |
19 | return self.renderToken(tokens, idx, options) | |
20 | } | |
21 | ||
22 | this.markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) { | |
23 | // If you are sure other plugins can't add `target` - drop check below | |
24 | const aIndex = tokens[idx].attrIndex('target') | |
25 | ||
26 | if (aIndex < 0) { | |
27 | tokens[idx].attrPush(['target', '_blank']) // add new attribute | |
28 | } else { | |
29 | tokens[idx].attrs[aIndex][1] = '_blank' // replace value of existing attr | |
30 | } | |
31 | ||
32 | // pass token to default renderer. | |
33 | return defaultRender(tokens, idx, options, env, self) | |
34 | } | |
35 | } | |
36 | ||
37 | markdownToHTML (markdown: string) { | |
38 | return this.markdownIt.render(markdown) | |
39 | } | |
40 | } |