2019-01-14 15:48:38 +00:00
|
|
|
import { Injectable } from '@angular/core'
|
2022-02-04 09:31:54 +00:00
|
|
|
import { getCustomMarkupSanitizeOptions, getDefaultSanitizeOptions } from '@shared/core-utils/renderer/html'
|
2020-06-23 12:10:17 +00:00
|
|
|
import { LinkifierService } from './linkifier.service'
|
2019-01-14 15:48:38 +00:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class HtmlRendererService {
|
2020-07-28 07:57:16 +00:00
|
|
|
private sanitizeHtml: typeof import ('sanitize-html')
|
2019-01-14 15:48:38 +00:00
|
|
|
|
|
|
|
constructor (private linkifier: LinkifierService) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-07-28 07:57:16 +00:00
|
|
|
async convertToBr (text: string) {
|
|
|
|
await this.loadSanitizeHtml()
|
|
|
|
|
|
|
|
const html = text.replace(/\r?\n/g, '<br />')
|
|
|
|
|
|
|
|
return this.sanitizeHtml(html, {
|
|
|
|
allowedTags: [ 'br' ]
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-05-27 13:59:55 +00:00
|
|
|
async toSafeHtml (text: string, additionalAllowedTags: string[] = []) {
|
2020-11-19 15:23:19 +00:00
|
|
|
const [ html ] = await Promise.all([
|
|
|
|
// Convert possible markdown to html
|
|
|
|
this.linkifier.linkify(text),
|
2019-02-15 14:52:18 +00:00
|
|
|
|
2020-11-19 15:23:19 +00:00
|
|
|
this.loadSanitizeHtml()
|
|
|
|
])
|
2019-01-14 15:48:38 +00:00
|
|
|
|
2021-05-27 13:59:55 +00:00
|
|
|
const options = additionalAllowedTags.length !== 0
|
|
|
|
? getCustomMarkupSanitizeOptions(additionalAllowedTags)
|
2022-02-04 09:31:54 +00:00
|
|
|
: getDefaultSanitizeOptions()
|
2021-05-27 13:59:55 +00:00
|
|
|
|
|
|
|
return this.sanitizeHtml(html, options)
|
2019-01-14 15:48:38 +00:00
|
|
|
}
|
2020-07-28 07:57:16 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2019-01-14 15:48:38 +00:00
|
|
|
}
|