/
markdown.directive.ts
57 lines (45 loc) · 1.36 KB
/
markdown.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Directive, ElementRef, Input, OnChanges, Renderer2 } from '@angular/core';
import { renderMarkdown } from '@app/framework/internal';
@Directive({
selector: '[sqxMarkdown]',
})
export class MarkdownDirective implements OnChanges {
@Input('sqxMarkdown')
public markdown!: string;
@Input()
public inline = true;
@Input()
public optional = false;
constructor(
private readonly element: ElementRef,
private readonly renderer: Renderer2,
) {
}
public ngOnChanges() {
let html = '';
let markdown = this.markdown;
const hasExclamation = markdown.indexOf('!') === 0;
if (hasExclamation) {
markdown = markdown.substring(1);
}
if (!markdown) {
html = markdown;
} else if (this.optional && !hasExclamation) {
html = markdown;
} else if (this.markdown) {
html = renderMarkdown(markdown, this.inline);
}
const hasHtml = html.indexOf('<') >= 0;
if (hasHtml) {
this.renderer.setProperty(this.element.nativeElement, 'innerHTML', html);
} else {
this.renderer.setProperty(this.element.nativeElement, 'textContent', html);
}
}
}