masquitos

Untitled

Jul 6th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {
  2.   AfterViewInit,
  3.   Component,
  4.   EventEmitter,
  5.   Input,
  6.   OnChanges,
  7.   OnDestroy,
  8.   OnInit,
  9.   Output,
  10.   SimpleChanges,
  11.   ViewChild
  12. } from "@angular/core";
  13. import { MyData } from "../../model/store/store";
  14. import { Message, MessageStatus, VmMessages } from "../../model/chat/message";
  15. import { UserInfo } from "../../model/other/other";
  16. import { MyStatus } from "../../model/status/myStatus";
  17. import { Messages } from "../../helper/messages";
  18. import { ScreenSize } from "../../model/screen/screen";
  19. import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
  20. import { UserInfoComponent } from "../dialogs/user-info/user-info.component";
  21. import { LoginInfoComponent } from "../dialogs/login-info/login-info.component";
  22. import { NgScrollbar } from "ngx-scrollbar";
  23. import { Observable, Subject } from "rxjs";
  24. import { filter, takeUntil, tap } from "rxjs/operators";
  25. import { MAX_MESSAGE_LENGTH } from "../../helper/constants";
  26. import { MyParser } from "../../helper/myParser";
  27.  
  28. @Component({
  29.   selector: "app-chat",
  30.   templateUrl: "./chat.component.html",
  31.   styleUrls: ["./chat.component.css"]
  32. })
  33. export class ChatComponent
  34.   implements OnInit, AfterViewInit, OnDestroy, OnChanges {
  35.   @ViewChild("ngScrollbar", { static: true }) ngScrollbar: NgScrollbar;
  36.   @Input() scrollBottom$: Observable<void>;
  37.   @Input() mdVmMessages: MyData<VmMessages>;
  38.   @Input() screenSize: ScreenSize;
  39.   @Input() currUserInfo: UserInfo;
  40.   @Output() loadChange: EventEmitter<void> = new EventEmitter<void>();
  41.   @Output() messageChange: EventEmitter<Message> = new EventEmitter<Message>();
  42.   @Output() readChange: EventEmitter<void> = new EventEmitter<void>();
  43.   public status: any = MyStatus;
  44.   public txtWrite: string = Messages.WRITE_YOUR_MESSAGE;
  45.   public txtError: string = Messages.ERROR_LOAD_MESSAGES;
  46.   public txtMessagesLoading: string = Messages.MESSAGES_LOADING;
  47.   public messageText: string = "";
  48.   public size: any = ScreenSize;
  49.   public txtErrorLoadData: string = Messages.ERROR_DATA_LOADING;
  50.   public badgeCount: number;
  51.   private componentDestroyed: Subject<any> = new Subject();
  52.   private maxMessageLength: number = MAX_MESSAGE_LENGTH;
  53.   private isScrolled: boolean;
  54.  
  55.   constructor(private dialog: MatDialog) {}
  56.  
  57.   ngOnInit() {}
  58.  
  59.   ngAfterViewInit(): void {
  60.     // this.scrollToBottom();
  61.     //
  62.     // this.scrollBottom$
  63.     //   .pipe(takeUntil(this.componentDestroyed))
  64.     //   .subscribe(data => {
  65.     //     this.scrollToBottom();
  66.     //     // если срола нет, но нужно прочест сообщения
  67.     //     this.setMessagesIsRead();
  68.     //   });
  69.  
  70.     // this.ngScrollbar.scrollable.elementScrolled().subscribe(e => {
  71.     //   console.log("прокрутили скролл", e);
  72.     //   this.isScrolled = true;
  73.     //   const el: HTMLElement = e.target as HTMLElement;
  74.     //   if (el.scrollTop === el.scrollHeight - el.clientHeight) {
  75.     //     this.isScrolled = false;
  76.     //     console.log(
  77.     //       "сбрасываем скролл, т.к достигли низа",
  78.     //       el.scrollTop,
  79.     //       el.scrollHeight,
  80.     //       el.clientHeight
  81.     //     );
  82.     //     this.setMessagesIsRead();
  83.     //   }
  84.     // });
  85.   }
  86.  
  87.   public onLoad() {
  88.     this.loadChange.emit();
  89.   }
  90.  
  91.   onSendMessage() {
  92.     const splitText: string[] = this.splitText(this.messageText);
  93.     splitText
  94.       .filter(el => el !== "")
  95.       .forEach(el => {
  96.         const message: Message = {
  97.           id: new Date().getTime(),
  98.           userId: this.currUserInfo.id,
  99.           text: el,
  100.           convId: this.mdVmMessages.data.conversationId,
  101.           time: new Date(),
  102.           isRead: false,
  103.           totalCount: null,
  104.           status: MessageStatus.PENDING
  105.         };
  106.         this.messageChange.emit(message);
  107.       });
  108.     this.messageText = "";
  109.     // this.scrollToBottom();
  110.   }
  111.  
  112.   private splitText(text: string): string[] {
  113.     return text
  114.       .split("")
  115.       .reduce((acc, rec, index) => {
  116.         return index % this.maxMessageLength || !index
  117.           ? acc.concat(rec)
  118.           : acc.concat(",", rec);
  119.       }, "")
  120.       .split(",");
  121.   }
  122.  
  123.   // Без задержки библиотека не обновляет кролл в самый низ
  124.   private scrollToBottom() {
  125.     // this.isScrolled = false;
  126.     // setTimeout(() => {
  127.     //   if (this.ngScrollbar) {
  128.     //     console.log("скролим в низ до упора");
  129.     //     this.ngScrollbar.update();
  130.     //     this.ngScrollbar.scrollToBottom().subscribe();
  131.     //   }
  132.     // });
  133.   }
  134.  
  135.   private setMessagesIsRead() {
  136.     console.log("setMessagesIsRead");
  137.     if (
  138.       (this.mdVmMessages.data.conversationStatus === MyStatus.LOADED ||
  139.         this.mdVmMessages.data.conversationStatus === MyStatus.SENDED) &&
  140.       (this.mdVmMessages.status === MyStatus.LOADED ||
  141.         this.mdVmMessages.status === MyStatus.SENDED)
  142.     ) {
  143.       console.log("setMessagesIsRead filter");
  144.       const filterd = this.mdVmMessages.data.messages.filter(
  145.         el =>
  146.           el.status === MessageStatus.LOADED ||
  147.           el.status === MessageStatus.RECEIVED ||
  148.           el.status === MessageStatus.SENDED
  149.       );
  150.  
  151.       const found = filterd.find(
  152.         el => el.userId !== this.currUserInfo.id && el.isRead === false
  153.       );
  154.       if (found) {
  155.         console.log("setMessagesIsRead emit");
  156.         this.readChange.emit();
  157.       }
  158.     }
  159.   }
  160.  
  161.   public onShowUser(data: number) {
  162.     if (data === this.currUserInfo.id) {
  163.       this.dialog.open(LoginInfoComponent);
  164.     } else {
  165.       const userInfo: UserInfo = this.mdVmMessages.data.userInfo;
  166.       const dialogConfig: MatDialogConfig = new MatDialogConfig<any>();
  167.       dialogConfig.data = userInfo;
  168.       this.dialog.open(UserInfoComponent, dialogConfig);
  169.     }
  170.   }
  171.  
  172.   public getNewMsgCount(): number {
  173.     return this.mdVmMessages.data.messages.filter(
  174.       el => el.userId !== this.currUserInfo.id && el.isRead === false
  175.     ).length;
  176.   }
  177.  
  178.   public parseBadge(data: number): string {
  179.     return MyParser.parseBadgeCount(data);
  180.   }
  181.  
  182.   ngOnDestroy(): void {
  183.     this.componentDestroyed.next();
  184.     this.componentDestroyed.complete();
  185.   }
  186.  
  187.   ngOnChanges(changes: SimpleChanges): void {
  188.     // const currValue: MyData<VmMessages> = changes["mdVmMessages"].currentValue;
  189.     // console.log("Детект смены данных");
  190.     // if (
  191.     //   (currValue.data.conversationStatus === MyStatus.LOADED ||
  192.     //     currValue.data.conversationStatus === MyStatus.SENDED) &&
  193.     //   (currValue.status === MyStatus.LOADED ||
  194.     //     currValue.status === MyStatus.SENDED)
  195.     // ) {
  196.     //   console.log("Данные загрузились");
  197.     //   const scrollElement = this.ngScrollbar.scrollable.getElementRef()
  198.     //     .nativeElement;
  199.     //   if (scrollElement.clientHeight > 0) {
  200.     //     console.log("контейнер показывается");
  201.     //     // Когда скролла нет
  202.     //     if (scrollElement.clientHeight >= scrollElement.scrollHeight) {
  203.     //       console.log("скролла нет");
  204.     //       this.setMessagesIsRead();
  205.     //     }
  206.     //     // Когда скролл есть
  207.     //     if (scrollElement.clientHeight < scrollElement.scrollHeight) {
  208.     //       console.log("скролл есть");
  209.     //       if (!this.isScrolled) {
  210.     //         console.log("крутим в низ т.к скрола не было");
  211.     //         this.scrollToBottom();
  212.     //       }
  213.     //     }
  214.     //   }
  215.     // }
  216.   }
  217. }
Add Comment
Please, Sign In to add comment