]>
Commit | Line | Data |
---|---|---|
1506307f | 1 | import { Injectable } from '@angular/core' |
67ed6552 | 2 | import { LinkifierService } from './linkifier.service' |
1506307f C |
3 | |
4 | @Injectable() | |
5 | export class HtmlRendererService { | |
d573926e | 6 | private sanitizeHtml: typeof import ('sanitize-html') |
1506307f C |
7 | |
8 | constructor (private linkifier: LinkifierService) { | |
9 | ||
10 | } | |
11 | ||
d573926e C |
12 | async convertToBr (text: string) { |
13 | await this.loadSanitizeHtml() | |
14 | ||
15 | const html = text.replace(/\r?\n/g, '<br />') | |
16 | ||
17 | return this.sanitizeHtml(html, { | |
18 | allowedTags: [ 'br' ] | |
19 | }) | |
20 | } | |
21 | ||
41d71344 | 22 | async toSafeHtml (text: string) { |
d573926e | 23 | await this.loadSanitizeHtml() |
41d71344 | 24 | |
1506307f C |
25 | // Convert possible markdown to html |
26 | const html = this.linkifier.linkify(text) | |
27 | ||
d573926e | 28 | return this.sanitizeHtml(html, { |
1aa75434 | 29 | allowedTags: [ 'a', 'p', 'span', 'br', 'strong', 'em', 'ul', 'ol', 'li' ], |
1506307f C |
30 | allowedSchemes: [ 'http', 'https' ], |
31 | allowedAttributes: { | |
891bc2ff | 32 | 'a': [ 'href', 'class', 'target', 'rel' ] |
1506307f C |
33 | }, |
34 | transformTags: { | |
35 | a: (tagName, attribs) => { | |
891bc2ff C |
36 | let rel = 'noopener noreferrer' |
37 | if (attribs.rel === 'me') rel += ' me' | |
38 | ||
1506307f C |
39 | return { |
40 | tagName, | |
41 | attribs: Object.assign(attribs, { | |
42 | target: '_blank', | |
891bc2ff | 43 | rel |
1506307f C |
44 | }) |
45 | } | |
46 | } | |
47 | } | |
48 | }) | |
49 | } | |
d573926e C |
50 | |
51 | private async loadSanitizeHtml () { | |
52 | // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function | |
53 | this.sanitizeHtml = (await import('sanitize-html') as any).default | |
54 | } | |
1506307f | 55 | } |