1 import truncate from 'lodash-es/truncate'
2 import { Subject } from 'rxjs'
3 import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
4 import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'
5 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
6 import { MarkdownService } from '@app/core'
9 selector: 'my-markdown-textarea',
10 templateUrl: './markdown-textarea.component.html',
11 styleUrls: [ './markdown-textarea.component.scss' ],
14 provide: NG_VALUE_ACCESSOR,
15 useExisting: forwardRef(() => MarkdownTextareaComponent),
21 export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit {
23 @Input() classes: string[] | { [klass: string]: any[] | any } = []
24 @Input() textareaMaxWidth = '100%'
25 @Input() textareaHeight = '150px'
26 @Input() truncate: number
27 @Input() markdownType: 'text' | 'enhanced' = 'text'
28 @Input() markdownVideo = false
29 @Input() name = 'description'
31 @ViewChild('textarea') textareaElement: ElementRef
33 truncatedPreviewHTML = ''
37 private contentChanged = new Subject<string>()
39 constructor (private markdownService: MarkdownService) {}
45 distinctUntilChanged()
47 .subscribe(() => this.updatePreviews())
49 this.contentChanged.next(this.content)
52 propagateChange = (_: any) => { /* empty */ }
54 writeValue (description: string) {
55 this.content = description
57 this.contentChanged.next(this.content)
60 registerOnChange (fn: (_: any) => void) {
61 this.propagateChange = fn
64 registerOnTouched () {
69 this.propagateChange(this.content)
71 this.contentChanged.next(this.content)
75 this.isMaximized = !this.isMaximized
77 // Make sure textarea have the focus
78 this.textareaElement.nativeElement.focus()
80 // Make sure the window has no scrollbars
81 if (!this.isMaximized) {
82 this.unlockBodyScroll()
88 private lockBodyScroll () {
89 document.getElementById('content').classList.add('lock-scroll')
92 private unlockBodyScroll () {
93 document.getElementById('content').classList.remove('lock-scroll')
96 private async updatePreviews () {
97 if (this.content === null || this.content === undefined) return
99 this.truncatedPreviewHTML = await this.markdownRender(truncate(this.content, { length: this.truncate }))
100 this.previewHTML = await this.markdownRender(this.content)
103 private async markdownRender (text: string) {
104 const html = this.markdownType === 'text' ?
105 await this.markdownService.textMarkdownToHTML(text) :
106 await this.markdownService.enhancedMarkdownToHTML(text)
108 return this.markdownVideo ? this.markdownService.processVideoTimestamps(html) : html