]>
Commit | Line | Data |
---|---|---|
1 | import { Injectable } from '@angular/core' | |
2 | ||
3 | import * as MarkdownIt from 'markdown-it' | |
4 | ||
5 | @Injectable() | |
6 | export class MarkdownService { | |
7 | private textMarkdownIt: MarkdownIt.MarkdownIt | |
8 | private linkifier: MarkdownIt.MarkdownIt | |
9 | private enhancedMarkdownIt: MarkdownIt.MarkdownIt | |
10 | ||
11 | constructor () { | |
12 | this.textMarkdownIt = new MarkdownIt('zero', { linkify: true, breaks: true }) | |
13 | .enable('linkify') | |
14 | .enable('autolink') | |
15 | .enable('emphasis') | |
16 | .enable('link') | |
17 | .enable('newline') | |
18 | .enable('list') | |
19 | this.setTargetToLinks(this.textMarkdownIt) | |
20 | ||
21 | this.enhancedMarkdownIt = new MarkdownIt('zero', { linkify: true, breaks: true }) | |
22 | .enable('linkify') | |
23 | .enable('autolink') | |
24 | .enable('emphasis') | |
25 | .enable('link') | |
26 | .enable('newline') | |
27 | .enable('list') | |
28 | .enable('image') | |
29 | this.setTargetToLinks(this.enhancedMarkdownIt) | |
30 | ||
31 | this.linkifier = new MarkdownIt('zero', { linkify: true }) | |
32 | .enable('linkify') | |
33 | this.setTargetToLinks(this.linkifier) | |
34 | } | |
35 | ||
36 | textMarkdownToHTML (markdown: string) { | |
37 | const html = this.textMarkdownIt.render(markdown) | |
38 | ||
39 | return this.avoidTruncatedLinks(html) | |
40 | } | |
41 | ||
42 | enhancedMarkdownToHTML (markdown: string) { | |
43 | const html = this.enhancedMarkdownIt.render(markdown) | |
44 | ||
45 | return this.avoidTruncatedLinks(html) | |
46 | } | |
47 | ||
48 | linkify (text: string) { | |
49 | const html = this.linkifier.render(text) | |
50 | ||
51 | return this.avoidTruncatedLinks(html) | |
52 | } | |
53 | ||
54 | private setTargetToLinks (markdownIt: MarkdownIt.MarkdownIt) { | |
55 | // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer | |
56 | const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) { | |
57 | return self.renderToken(tokens, idx, options) | |
58 | } | |
59 | ||
60 | markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) { | |
61 | // If you are sure other plugins can't add `target` - drop check below | |
62 | const aIndex = tokens[idx].attrIndex('target') | |
63 | ||
64 | if (aIndex < 0) { | |
65 | tokens[idx].attrPush(['target', '_blank']) // add new attribute | |
66 | } else { | |
67 | tokens[idx].attrs[aIndex][1] = '_blank' // replace value of existing attr | |
68 | } | |
69 | ||
70 | // pass token to default renderer. | |
71 | return defaultRender(tokens, idx, options, env, self) | |
72 | } | |
73 | } | |
74 | ||
75 | private avoidTruncatedLinks (html) { | |
76 | return html.replace(/<a[^>]+>([^<]+)<\/a>\s*...(<\/p>)?$/mi, '$1...') | |
77 | } | |
78 | } |