import { CommonModule } from '@angular/common'; import { Component, ElementRef, EventEmitter, Input, Output, ViewChild, } from '@angular/core'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { from } from 'rxjs'; //Pipe import { IconUrlPipe } from './pipes'; import { DateFormatPipe } from '../../pipes/date.pipe'; //Model import { CommentConfig, DeleteCommentData, SaveCommentData, UpdateCommentData, } from './models'; //Directive import { AutoResizeDirective } from './directives'; //Enum import { CommentAction } from './enums'; //Components import { CaAppTooltipV2Component } from '../ca-app-tooltip-v2/ca-app-tooltip-v2.component'; //Modal import { CommentModalComponent } from './modals/comment-modal/comment-modal.component'; //Services import { AppModalService } from './services'; @Component({ selector: 'app-ca-comment', imports: [ //modules CommonModule, AngularSvgIconModule, NgbTooltip, //pipes DateFormatPipe, IconUrlPipe, //components CaAppTooltipV2Component, //directive AutoResizeDirective, ], templateUrl: './ca-comment.component.html', styleUrls: ['./ca-comment.component.scss'] }) export class CaCommentComponent { constructor(private modalService: AppModalService) {} @ViewChild('commentTextarea') commentTextarea!: ElementRef; @Input() set config(data: CommentConfig) { this.commentConfig = data; if (!data.id) { this.isEditMode = true; } } @Output() onSave = new EventEmitter(); @Output() onUpdate = new EventEmitter(); @Output() onDelete = new EventEmitter(); public action = CommentAction; public commentConfig!: CommentConfig; public isEditMode: boolean = false; ngAfterViewInit(): void { this.commentTextarea.nativeElement.value = this.commentConfig.content; } public onAction(action: CommentAction): void { switch (action) { case CommentAction.CANCEL: { if (this.commentConfig.id) { this.isEditMode = false; } this.commentTextarea.nativeElement.value = this.commentConfig.content; break; } case CommentAction.CONFIRM: { const textareaContent = this.commentTextarea.nativeElement.value; // update comment if (this.commentConfig.id && this.commentConfig.owner) { this.onUpdate.emit({ id: this.commentConfig.id, content: textareaContent, }); } // save new comment if (!this.commentConfig.id) { this.onSave.emit({ content: textareaContent, }); } this.isEditMode = false; break; } case CommentAction.DELETE: { if (this.commentConfig.id && this.commentConfig.owner) { const modalRef = this.modalService.open(CommentModalComponent); modalRef.componentInstance.config = this.commentConfig; from(modalRef.result).subscribe({ next: (result) => { if (result === 'confirm') { if (this.commentConfig.id) { this.onDelete.emit({ id: this.commentConfig.id }); } } }, error: (err) => { console.log(err); }, }); } break; } case CommentAction.EDIT: { this.isEditMode = true; this.commentTextarea.nativeElement.focus(); break; } default: { new Error('Unsupported action'); } } } }