1 import { Injectable } from '@angular/core'
3 import * as MarkdownIt from 'markdown-it'
6 export class MarkdownService {
7 private markdownIt: MarkdownIt.MarkdownIt
8 private linkifier: MarkdownIt.MarkdownIt
11 this.markdownIt = new MarkdownIt('zero', { linkify: true, breaks: true })
18 this.setTargetToLinks(this.markdownIt)
20 this.linkifier = new MarkdownIt('zero', { linkify: true })
22 this.setTargetToLinks(this.linkifier)
25 markdownToHTML (markdown: string) {
26 const html = this.markdownIt.render(markdown)
28 // Avoid linkify truncated links
29 return html.replace(/<a[^>]+>([^<]+)<\/a>\s*...(<\/p>)?$/mi, '$1...')
32 linkify (text: string) {
33 return this.linkifier.render(text)
36 private setTargetToLinks (markdownIt: MarkdownIt.MarkdownIt) {
37 // Snippet from markdown-it documentation: https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
38 const defaultRender = markdownIt.renderer.rules.link_open || function (tokens, idx, options, env, self) {
39 return self.renderToken(tokens, idx, options)
42 markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) {
43 // If you are sure other plugins can't add `target` - drop check below
44 const aIndex = tokens[idx].attrIndex('target')
47 tokens[idx].attrPush(['target', '_blank']) // add new attribute
49 tokens[idx].attrs[aIndex][1] = '_blank' // replace value of existing attr
52 // pass token to default renderer.
53 return defaultRender(tokens, idx, options, env, self)