1 import { ViewportScroller } from '@angular/common'
2 import truncate from 'lodash-es/truncate'
3 import { Subject } from 'rxjs'
4 import { debounceTime, distinctUntilChanged } from 'rxjs/operators'
5 import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'
6 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
7 import { MarkdownService } from '@app/core'
10 selector: 'my-markdown-textarea',
11 templateUrl: './markdown-textarea.component.html',
12 styleUrls: [ './markdown-textarea.component.scss' ],
15 provide: NG_VALUE_ACCESSOR,
16 useExisting: forwardRef(() => MarkdownTextareaComponent),
22 export class MarkdownTextareaComponent implements ControlValueAccessor, OnInit {
24 @Input() classes: string[] | { [klass: string]: any[] | any } = []
25 @Input() textareaMaxWidth = '100%'
26 @Input() textareaHeight = '150px'
27 @Input() truncate: number
28 @Input() markdownType: 'text' | 'enhanced' = 'text'
29 @Input() markdownVideo = false
30 @Input() name = 'description'
32 @ViewChild('textarea') textareaElement: ElementRef
34 truncatedPreviewHTML = ''
38 private contentChanged = new Subject<string>()
39 private scrollPosition: [number, number]
42 private viewportScroller: ViewportScroller,
43 private markdownService: MarkdownService
50 distinctUntilChanged()
52 .subscribe(() => this.updatePreviews())
54 this.contentChanged.next(this.content)
57 propagateChange = (_: any) => { /* empty */ }
59 writeValue (description: string) {
60 this.content = description
62 this.contentChanged.next(this.content)
65 registerOnChange (fn: (_: any) => void) {
66 this.propagateChange = fn
69 registerOnTouched () {
74 this.propagateChange(this.content)
76 this.contentChanged.next(this.content)
80 this.isMaximized = !this.isMaximized
82 // Make sure textarea have the focus
83 this.textareaElement.nativeElement.focus()
85 // Make sure the window has no scrollbars
86 if (!this.isMaximized) {
87 this.unlockBodyScroll()
93 private lockBodyScroll () {
94 this.scrollPosition = this.viewportScroller.getScrollPosition()
95 document.getElementById('content').classList.add('lock-scroll')
98 private unlockBodyScroll () {
99 document.getElementById('content').classList.remove('lock-scroll')
100 this.viewportScroller.scrollToPosition(this.scrollPosition)
103 private async updatePreviews () {
104 if (this.content === null || this.content === undefined) return
106 this.truncatedPreviewHTML = await this.markdownRender(truncate(this.content, { length: this.truncate }))
107 this.previewHTML = await this.markdownRender(this.content)
110 private async markdownRender (text: string) {
111 const html = this.markdownType === 'text' ?
112 await this.markdownService.textMarkdownToHTML(text) :
113 await this.markdownService.enhancedMarkdownToHTML(text)
115 return this.markdownVideo ? this.markdownService.processVideoTimestamps(html) : html