import { Component, OnInit, Input, AfterViewInit, ViewChild, ElementRef, AfterViewChecked, Output, EventEmitter } from '@angular/core'; import { KstConfig } from './config/chat.config'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { LoginChat, Init } from './store/chat.actions/actions'; import { CharAuthorizeService } from './services/chat-authorize.service'; import { IChatState } from './store/reducers/chat.state'; import { User } from './store/entities/user'; import { ChatHelper } from './utils/chatHelper'; import { ChatMessage, PostMessage } from './store/entities'; @Component({ // tslint:disable-next-line: component-selector selector: 'kst-chat', template: `
` }) export class KstChatComponent implements OnInit, AfterViewInit, AfterViewChecked { @Input('user') user: User; @Input('channel') channelNameOrId: string; @ViewChild('container') container: ElementRef; // tslint:disable-next-line: no-output-on-prefix @Output('onMessage') onMessage = new EventEmitter(); // tslint:disable-next-line: no-output-on-prefix @Output('onClickUser') onClickUser = new EventEmitter(); // 初始状态 chatState: Observable; userName: string; token: string; messages: ChatMessage[] = []; channel: any; constructor( private _store: Store, private _authorizeService: CharAuthorizeService) { this.chatState = this._store.pipe(select((state: any) => { return state[KstConfig.stateName].chat; })); } ngOnInit(): void { const self = this; this._store.dispatch(new Init(this.user)); this.chatState.subscribe(data => { if (data.appUser) { self.userName = data.appUser.username; self.token = data.appUser.accessToken; } self.messages = self.getLastMessage(data.messages, 25); self.channel = data.channel; }); if (self.user) { // 自动登陆 self._authorizeService.login(self.user.username, self.user.chatpwd, self.channelNameOrId); } } ngAfterViewInit(): void { setTimeout(() => { this.scrollToBottom(); }, 800); } ngAfterViewChecked(): void { } onTouchMessage(event) { this.onMessage.emit(event); } scrollToBottom(): void { try { this.container.nativeElement.querySelector('.chats').scrollTop = this.container.nativeElement.querySelector('.chats').scrollHeight; } catch (err) { } } getAvatar(username: string) { return `${KstConfig.url}/avatar/${username}?_dc=0`; } convertEmoji(str: string) { return ChatHelper.convertMessage(str); } mentionsConvert(mentions: any[]) { return mentions.map(m => { return `${m.username}`; }).join(''); } clickUser(username: string) { this.onClickUser.emit(username); } /** * 获取最近的指定数量的消息 * @param count */ getLastMessage(msgs: ChatMessage[], count: number = 15) { return msgs.filter((m, i) => i >= msgs.length - count); } isAbsoluteUrl(url: string) { return url.startsWith('http://') || url.startsWith('https://') || url.startsWith('www.'); } }