import { Injectable } from '@angular/core'
+import { getCustomMarkupSanitizeOptions, getDefaultSanitizeOptions } from '@shared/core-utils/renderer/html'
import { LinkifierService } from './linkifier.service'
@Injectable()
export class HtmlRendererService {
+ private sanitizeHtml: typeof import ('sanitize-html')
constructor (private linkifier: LinkifierService) {
}
- async toSafeHtml (text: string) {
- // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function
- const sanitizeHtml: typeof import ('sanitize-html') = (await import('sanitize-html') as any).default
-
- // Convert possible markdown to html
- const html = this.linkifier.linkify(text)
-
- return sanitizeHtml(html, {
- allowedTags: [ 'a', 'p', 'span', 'br', 'strong', 'em', 'ul', 'ol', 'li' ],
- allowedSchemes: [ 'http', 'https' ],
- allowedAttributes: {
- 'a': [ 'href', 'class', 'target', 'rel' ]
- },
- transformTags: {
- a: (tagName, attribs) => {
- let rel = 'noopener noreferrer'
- if (attribs.rel === 'me') rel += ' me'
-
- return {
- tagName,
- attribs: Object.assign(attribs, {
- target: '_blank',
- rel
- })
- }
- }
- }
+ async convertToBr (text: string) {
+ await this.loadSanitizeHtml()
+
+ const html = text.replace(/\r?\n/g, '<br />')
+
+ return this.sanitizeHtml(html, {
+ allowedTags: [ 'br' ]
})
}
+
+ async toSafeHtml (text: string, additionalAllowedTags: string[] = []) {
+ const [ html ] = await Promise.all([
+ // Convert possible markdown to html
+ this.linkifier.linkify(text),
+
+ this.loadSanitizeHtml()
+ ])
+
+ const options = additionalAllowedTags.length !== 0
+ ? getCustomMarkupSanitizeOptions(additionalAllowedTags)
+ : getDefaultSanitizeOptions()
+
+ return this.sanitizeHtml(html, options)
+ }
+
+ private async loadSanitizeHtml () {
+ // FIXME: import('..') returns a struct module, containing a "default" field corresponding to our sanitizeHtml function
+ this.sanitizeHtml = (await import('sanitize-html') as any).default
+ }
}