Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- AfterViewInit,
- Component,
- EventEmitter,
- Input,
- OnChanges,
- OnDestroy,
- OnInit,
- Output,
- SimpleChanges,
- ViewChild
- } from "@angular/core";
- import { MyData } from "../../model/store/store";
- import { Message, MessageStatus, VmMessages } from "../../model/chat/message";
- import { UserInfo } from "../../model/other/other";
- import { MyStatus } from "../../model/status/myStatus";
- import { Messages } from "../../helper/messages";
- import { ScreenSize } from "../../model/screen/screen";
- import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
- import { UserInfoComponent } from "../dialogs/user-info/user-info.component";
- import { LoginInfoComponent } from "../dialogs/login-info/login-info.component";
- import { NgScrollbar } from "ngx-scrollbar";
- import { Observable, Subject } from "rxjs";
- import { filter, takeUntil, tap } from "rxjs/operators";
- import { MAX_MESSAGE_LENGTH } from "../../helper/constants";
- import { MyParser } from "../../helper/myParser";
- @Component({
- selector: "app-chat",
- templateUrl: "./chat.component.html",
- styleUrls: ["./chat.component.css"]
- })
- export class ChatComponent
- implements OnInit, AfterViewInit, OnDestroy, OnChanges {
- @ViewChild("ngScrollbar", { static: true }) ngScrollbar: NgScrollbar;
- @Input() scrollBottom$: Observable<void>;
- @Input() mdVmMessages: MyData<VmMessages>;
- @Input() screenSize: ScreenSize;
- @Input() currUserInfo: UserInfo;
- @Output() loadChange: EventEmitter<void> = new EventEmitter<void>();
- @Output() messageChange: EventEmitter<Message> = new EventEmitter<Message>();
- @Output() readChange: EventEmitter<void> = new EventEmitter<void>();
- public status: any = MyStatus;
- public txtWrite: string = Messages.WRITE_YOUR_MESSAGE;
- public txtError: string = Messages.ERROR_LOAD_MESSAGES;
- public txtMessagesLoading: string = Messages.MESSAGES_LOADING;
- public messageText: string = "";
- public size: any = ScreenSize;
- public txtErrorLoadData: string = Messages.ERROR_DATA_LOADING;
- public badgeCount: number;
- private componentDestroyed: Subject<any> = new Subject();
- private maxMessageLength: number = MAX_MESSAGE_LENGTH;
- private isScrolled: boolean;
- constructor(private dialog: MatDialog) {}
- ngOnInit() {}
- ngAfterViewInit(): void {
- // this.scrollToBottom();
- //
- // this.scrollBottom$
- // .pipe(takeUntil(this.componentDestroyed))
- // .subscribe(data => {
- // this.scrollToBottom();
- // // если срола нет, но нужно прочест сообщения
- // this.setMessagesIsRead();
- // });
- // this.ngScrollbar.scrollable.elementScrolled().subscribe(e => {
- // console.log("прокрутили скролл", e);
- // this.isScrolled = true;
- // const el: HTMLElement = e.target as HTMLElement;
- // if (el.scrollTop === el.scrollHeight - el.clientHeight) {
- // this.isScrolled = false;
- // console.log(
- // "сбрасываем скролл, т.к достигли низа",
- // el.scrollTop,
- // el.scrollHeight,
- // el.clientHeight
- // );
- // this.setMessagesIsRead();
- // }
- // });
- }
- public onLoad() {
- this.loadChange.emit();
- }
- onSendMessage() {
- const splitText: string[] = this.splitText(this.messageText);
- splitText
- .filter(el => el !== "")
- .forEach(el => {
- const message: Message = {
- id: new Date().getTime(),
- userId: this.currUserInfo.id,
- text: el,
- convId: this.mdVmMessages.data.conversationId,
- time: new Date(),
- isRead: false,
- totalCount: null,
- status: MessageStatus.PENDING
- };
- this.messageChange.emit(message);
- });
- this.messageText = "";
- // this.scrollToBottom();
- }
- private splitText(text: string): string[] {
- return text
- .split("")
- .reduce((acc, rec, index) => {
- return index % this.maxMessageLength || !index
- ? acc.concat(rec)
- : acc.concat(",", rec);
- }, "")
- .split(",");
- }
- // Без задержки библиотека не обновляет кролл в самый низ
- private scrollToBottom() {
- // this.isScrolled = false;
- // setTimeout(() => {
- // if (this.ngScrollbar) {
- // console.log("скролим в низ до упора");
- // this.ngScrollbar.update();
- // this.ngScrollbar.scrollToBottom().subscribe();
- // }
- // });
- }
- private setMessagesIsRead() {
- console.log("setMessagesIsRead");
- if (
- (this.mdVmMessages.data.conversationStatus === MyStatus.LOADED ||
- this.mdVmMessages.data.conversationStatus === MyStatus.SENDED) &&
- (this.mdVmMessages.status === MyStatus.LOADED ||
- this.mdVmMessages.status === MyStatus.SENDED)
- ) {
- console.log("setMessagesIsRead filter");
- const filterd = this.mdVmMessages.data.messages.filter(
- el =>
- el.status === MessageStatus.LOADED ||
- el.status === MessageStatus.RECEIVED ||
- el.status === MessageStatus.SENDED
- );
- const found = filterd.find(
- el => el.userId !== this.currUserInfo.id && el.isRead === false
- );
- if (found) {
- console.log("setMessagesIsRead emit");
- this.readChange.emit();
- }
- }
- }
- public onShowUser(data: number) {
- if (data === this.currUserInfo.id) {
- this.dialog.open(LoginInfoComponent);
- } else {
- const userInfo: UserInfo = this.mdVmMessages.data.userInfo;
- const dialogConfig: MatDialogConfig = new MatDialogConfig<any>();
- dialogConfig.data = userInfo;
- this.dialog.open(UserInfoComponent, dialogConfig);
- }
- }
- public getNewMsgCount(): number {
- return this.mdVmMessages.data.messages.filter(
- el => el.userId !== this.currUserInfo.id && el.isRead === false
- ).length;
- }
- public parseBadge(data: number): string {
- return MyParser.parseBadgeCount(data);
- }
- ngOnDestroy(): void {
- this.componentDestroyed.next();
- this.componentDestroyed.complete();
- }
- ngOnChanges(changes: SimpleChanges): void {
- // const currValue: MyData<VmMessages> = changes["mdVmMessages"].currentValue;
- // console.log("Детект смены данных");
- // if (
- // (currValue.data.conversationStatus === MyStatus.LOADED ||
- // currValue.data.conversationStatus === MyStatus.SENDED) &&
- // (currValue.status === MyStatus.LOADED ||
- // currValue.status === MyStatus.SENDED)
- // ) {
- // console.log("Данные загрузились");
- // const scrollElement = this.ngScrollbar.scrollable.getElementRef()
- // .nativeElement;
- // if (scrollElement.clientHeight > 0) {
- // console.log("контейнер показывается");
- // // Когда скролла нет
- // if (scrollElement.clientHeight >= scrollElement.scrollHeight) {
- // console.log("скролла нет");
- // this.setMessagesIsRead();
- // }
- // // Когда скролл есть
- // if (scrollElement.clientHeight < scrollElement.scrollHeight) {
- // console.log("скролл есть");
- // if (!this.isScrolled) {
- // console.log("крутим в низ т.к скрола не было");
- // this.scrollToBottom();
- // }
- // }
- // }
- // }
- }
- }
Add Comment
Please, Sign In to add comment