UNPKG

zoriakinc-messaging

Version:

Angular Messaging Module

16 lines (14 loc) 20 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("@angular/common"),require("rxjs"),require("@angular/common/http"),require("rxjs/operators"),require("querystring"),require("@angular/platform-browser"),require("@angular/platform-browser/animations"),require("@angular/flex-layout"),require("@angular/material"),require("@angular/material-moment-adapter"),require("@angular/material/core"),require("@angular/forms")):"function"==typeof define&&define.amd?define("zoriakinc-messaging",["exports","@angular/core","@angular/common","rxjs","@angular/common/http","rxjs/operators","querystring","@angular/platform-browser","@angular/platform-browser/animations","@angular/flex-layout","@angular/material","@angular/material-moment-adapter","@angular/material/core","@angular/forms"],t):t((e=e||self)["zoriakinc-messaging"]={},e.ng.core,e.ng.common,e.rxjs,e.ng.common.http,e.rxjs.operators,e.querystring,e.ng.platformBrowser,e.ng.platformBrowser.animations,e.ng["flex-layout"],e.ng.material,e.ng["material-moment-adapter"],e.ng.material.core,e.ng.forms)}(this,(function(e,t,s,a,n,i,r,o,c,u,d,l,g,p){"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */var m=function(){return(m=Object.assign||function(e){for(var t,s=1,a=arguments.length;s<a;s++)for(var n in t=arguments[s])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)};var h=function(){function e(e,t,s){var n=this;this.http=e,this.injector=t,this.config=s,this.totalUnReadMsgsCountSource=new a.BehaviorSubject(0),this.totalUnReadMsgsCount=this.totalUnReadMsgsCountSource.asObservable(),this.unReadMsgsCountsArraySource=new a.BehaviorSubject([]),this.unReadMsgsCountsArray=this.unReadMsgsCountsArraySource.asObservable(),this.unreadMsgsIdsPairs={},this.isWebSocketReconnectingSource=new a.BehaviorSubject(!1),this.isWebSocketReconnecting=this.isWebSocketReconnectingSource.asObservable(),this.defaultMsgArrivalCallback=function(e){if(r.stringify(e.sender_user_id)in n.unreadMsgsIdsPairs){if(n.unreadMsgsIdsPairs[r.stringify(e.sender_user_id)].indexOf(e.id)>-1)return;n.unreadMsgsIdsPairs[r.stringify(e.sender_user_id)].push(e.id)}else n.unreadMsgsIdsPairs[r.stringify(e.sender_user_id)]=[e.id];n.incrementTotalUnReadMsgsCount();var t=n.unReadMsgsCountsArraySource.getValue(),s=t.findIndex((function(t){return t.sender_user_id===e.sender_user_id}));-1!==s?t[s].count+=1:t.push({sender_user_id:e.sender_user_id,count:1}),n.unReadMsgsCountsArraySource.next(t),console.log(t)},console.log("inside service: ",s),this.configObject=s,this.authService=this.injector.get(s.auth),s.push&&(this.pushService=this.injector.get(s.push)),console.log(this.authService),console.log(this.pushService)}return e.prototype.initialize=function(e){this.configObject=e},e.prototype.setTotalUnReadMsgsCount=function(e){this.totalUnReadMsgsCountSource.next(e)},e.prototype.setUnReadMsgsCountsArray=function(e){this.unReadMsgsCountsArraySource.next(e)},e.prototype.incrementTotalUnReadMsgsCount=function(){this.totalUnReadMsgsCountSource.next(this.totalUnReadMsgsCountSource.getValue()+1)},e.prototype.list=function(e,t){var s;return void 0===t&&(t=null),s=t?""+this.configObject.messages_url+t+"/?limit="+this.configObject.messages_page_size+"&offset="+e:this.configObject.messages_url+"?limit="+this.configObject.messages_page_size+"&offset="+e,this.http.get(s).pipe(i.map((function(e){return e.results})))},e.prototype.send_message=function(e,t){void 0===t&&(t=null),this.ws.send(JSON.stringify({content:e,donor_id:t}))},e.prototype.startLiveChat=function(e){var t=this;void 0===e&&(e=null),this.initializeUnReadMessagesCounts();var s=function(s){t.defaultMsgArrivalCallback(s),e&&e(s)},a=function(e){var t=JSON.parse(e.data).message;s(t)};this.ws&&this.ws.readyState===this.ws.OPEN?this.setWebSocketCallbacks(a):this.initializeAutoReconnectingWebSocket(a),this.pushService&&this.setNotificationCallback(s)},e.prototype.initializeAutoReconnectingWebSocket=function(e){var t=this;if(this.closeLiveChat(),this.authService.isAuthenticated()){var s=this.authService.getToken();this.ws=new WebSocket(this.configObject.socket_url+"?token="+s),this.ws.onopen=function(){return t.isWebSocketReconnectingSource.next(!1)},this.setWebSocketCallbacks(e)}},e.prototype.setWebSocketCallbacks=function(e){var t=this;this.ws.onmessage=e,this.ws.onclose=function(){t.isWebSocketReconnectingSource.next(!0),setTimeout((function(){t.initializeAutoReconnectingWebSocket(e)}),1e3)},this.ws.onerror=function(e){t.ws.close()}},e.prototype.initializeUnReadMessagesCounts=function(){var e=this;this.http.get(this.configObject.messages_url+"unread_messages_count/").subscribe((function(t){e.setUnReadMsgsCountsArray(t);var s=0;t.forEach((function(e){s+=e.count})),e.setTotalUnReadMsgsCount(s)}))},e.prototype.setNotificationCallback=function(e){this.pushService.setNotificationCallback((function(t){var s=t.additionalData.message_dict;e(s)}))},e.prototype.removeOnMessageListener=function(){this.ws&&(this.ws.onmessage=this.defaultMsgArrivalCallback),this.pushService&&this.pushService.setNotificationCallback(this.defaultMsgArrivalCallback)},e.prototype.closeLiveChat=function(){var e=this;this.ws&&(this.ws.onclose=function(t){delete e.ws},this.ws.close())},e.prototype.readAll=function(e){var t,s=this;return void 0===e&&(e=null),t=e?""+this.configObject.messages_url+e+"/read_all/":this.configObject.messages_url+"read_all/",this.http.patch(t,{}).pipe(i.tap((function(e){return s.setTotalUnReadMsgsCount(0)})))},e.prototype.unreadLatest=function(e){return this.http.patch(""+this.configObject.messages_url+e+"/unread_latest/",{})},e.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],e.ctorParameters=function(){return[{type:n.HttpClient},{type:t.Injector},{type:void 0,decorators:[{type:t.Inject,args:["config"]}]}]},e.ngInjectableDef=t.ɵɵdefineInjectable({factory:function(){return new e(t.ɵɵinject(n.HttpClient),t.ɵɵinject(t.INJECTOR),t.ɵɵinject("config"))},token:e,providedIn:"root"}),e}();var f=function(){function e(e){this.messagingService=e,this.messageList=[],this.groupedMessageList=[],this.GROUP_MIN_RANGE_IN_MINUTES=20,this.isFullScreenMode=!1,this.showSenderName=!0,this.replyContent="",this.messagingService.configObject.theme_color&&document.documentElement.style.setProperty("--theme-color",this.messagingService.configObject.theme_color),this.isFullScreenMode=this.messagingService.configObject.full_screen_mode,this.isFullScreenMode&&document.documentElement.style.setProperty("--window-width","100%"),"show_sender_name"in this.messagingService.configObject&&(this.showSenderName=this.messagingService.configObject.show_sender_name),this.isLoading=!0}return e.prototype.ngOnInit=function(){var e=this,t=this.messagingService.readAll(this.donor_id);t.subscribe();var s=this.loadMessages(0);s.subscribe((function(t){e.messageList=t,e.addNewMessagesPage(t)})),a.forkJoin(t,s).subscribe((function(){return e.isLoading=!1}));this.messagingService.startLiveChat((function(t){e.messageList.some((function(e){return e.id===t.id}))||e.recipient_user_id&&parseInt(t.sender_user_id)!==parseInt(e.recipient_user_id)&&parseInt(t.recipient_user_id)!==parseInt(e.recipient_user_id)||(e.addNewMessage(m({id:t.id,content:t.content,created_at:t.created_at,is_self_message:t.sender_user_id===e.user_id},!t.is_donor_message&&{sender_display_name:e.user_display_name})),e.messageList.push(t),e.messagingService.readAll(e.donor_id).subscribe())}))},e.prototype.loadMore=function(){var e=this;this.isLoading=!0;var t=this.loadMessages(this.messageList.length).subscribe((function(s){e.messageList=s.concat(e.messageList),e.addNewMessagesPage(s),e.isLoading=!1,t.unsubscribe()}))},e.prototype.loadMessages=function(e){var t=this;return this.messagingService.list(e,this.donor_id).pipe(i.map((function(e){return e.reverse(),e.map((function(e){return{id:e.id,content:e.content,created_at:e.created_at,is_self_message:e.sender===t.user_id,sender_display_name:e.sender_display_name}}))})))},e.prototype.ngAfterViewInit=function(){var e=this;this.chatContainerElement.nativeElement.style.height=this.height||"calc(100vh - 500px)",this.msgDivs&&this.msgDivs.last&&this.msgDivs.last.nativeElement.focus(),this.msgDivs.changes.subscribe((function(){e.msgDivs&&e.msgDivs.last&&e.msgDivs.last.nativeElement.focus()}))},e.prototype.addNewMessage=function(e){this.latestMsgDatetime&&(new Date(e.created_at.toString()).getTime()-this.latestMsgDatetime.getTime())/6e4<this.GROUP_MIN_RANGE_IN_MINUTES?this.groupedMessageList[this.groupedMessageList.length-1].push(e):this.groupedMessageList.push([e]),this.latestMsgDatetime=new Date(e.created_at.toString())},e.prototype.addNewMessagesPage=function(e){var t=this;if(this.msgDivs&&this.msgDivs.first){var s=this.msgDivs.first,a=function(){s.nativeElement.scrollIntoView(!0),t.msgsContainer.nativeElement.scrollBy(0,-90)};this.msgsContainer.nativeElement.addEventListener("DOMNodeInserted",a,!1),setTimeout((function(){return t.msgsContainer.nativeElement.removeEventListener("DOMNodeInserted",a,!1)}))}var n=this.groupByTime(e);n&&(this.groupedMessageList=n.groupedList.concat(this.groupedMessageList),this.latestMsgDatetime=n.latestMsgDatetime)},e.prototype.groupByTime=function(e){var t=this;if(e.length){var s=[],a=[],n=new Date(e[0].created_at.toString());return e.forEach((function(e){(new Date(e.created_at.toString()).getTime()-n.getTime())/6e4<t.GROUP_MIN_RANGE_IN_MINUTES?(a.push(e),n=new Date(e.created_at.toString())):(s.push(a),a=[e],n=new Date(e.created_at.toString()))})),s.push(a),{groupedList:s,latestMsgDatetime:n}}},e.prototype.reply=function(){this.messagingService.send_message(this.replyContent,this.donor_id),this.replyContent="",this.msgInput.nativeElement.addEventListener("focusout",this.focusOnInputAgain.bind(this))},e.prototype.focusOnInputAgain=function(e){var t=this;setTimeout((function(){t.msgInput.nativeElement.focus(),t.msgInput.nativeElement.removeEventListener("focusout",t.focusOnInputAgain.bind(t))}))},e.prototype.onScroll=function(e){0===e.target.scrollTop&&this.loadMore()},e.prototype.isToday=function(e){e=new Date(e.toString());var t=new Date;return e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()},e.prototype.isYesterday=function(e){e=new Date(e.toString());var t=new Date;t.setDate(t.getDate()-1);var s=t;return e.getDate()===s.getDate()&&e.getMonth()===s.getMonth()&&e.getFullYear()===s.getFullYear()},e.prototype.isWeekDay=function(e){if(this.isToday(e)||this.isYesterday(e))return!1;var t=new Date;return t.setDate(t.getDate()-7),new Date(e.toString())>t},e.prototype.getDayName=function(e){return new Date(e.toString()).toLocaleString("en-us",{weekday:"short"})},e.prototype.ngOnDestroy=function(){this.messagingService.removeOnMessageListener()},e.decorators=[{type:t.Component,args:[{selector:"lib-chat-box",template:'<div class="chatbox" #chatContainer>\n\n <div *ngIf="recipient_display_name && !isFullScreenMode" class="chat-header">\n <span class="avatar">\n <mat-icon *ngIf="!recipient_avatar_src" class="avatar__icon">person</mat-icon>\n <img *ngIf="recipient_avatar_src" [src]="recipient_avatar_src" class="avatar__img">\n </span>\n <span class="name">\n {{recipient_display_name}}\n </span>\n </div>\n\n <div class="messages" #msgsContainer (scroll)="onScroll($event)">\n <div *ngFor="let group of groupedMessageList">\n <div class="messages-group">\n <div class="messages-group-label">\n <div class="hr-sect" *ngIf="isToday(group[0]?.created_at)">\n <span style="padding: 0 10px;">{{group[0]?.created_at | date: \'shortTime\'}}</span>\n </div>\n <div class="hr-sect" *ngIf="isYesterday(group[0]?.created_at)">\n <span style="padding: 0 10px;">Yesterday {{group[0]?.created_at | date: \'shortTime\'}}</span>\n </div>\n <div class="hr-sect" *ngIf="isWeekDay(group[0]?.created_at)">\n <span style="padding: 0 10px;">{{group[0]?.created_at | date: \'EEEE\'}} {{group[0]?.created_at | date: \'shortTime\'}}</span>\n </div>\n <div class="hr-sect" *ngIf="!isToday(group[0]?.created_at) &&\n !isYesterday(group[0]?.created_at) &&\n !isWeekDay(group[0]?.created_at)">\n <span style="padding: 0 10px;"> {{group[0]?.created_at | date: \'MMM d, y, h:mm a\'}}</span>\n </div>\n </div>\n <div tabindex="1" class="message-div" #msgDiv *ngFor="let message of group">\n <div class="text-icon" [class.self-messages]="message.is_self_message">\n <span class="avatar" *ngIf="!message.is_self_message">\n <mat-icon class="avatar__icon">person</mat-icon>\n <img *ngIf="recipient_avatar_src" [src]="recipient_avatar_src" class="avatar__img">\n </span>\n <div>\n <div class="sender-name" *ngIf="message.is_self_message && this.showSenderName">\n {{message.sender_display_name}}\n </div>\n <p class="message-item">\n {{message.content}}\n </p>\n </div>\n <span class="avatar" style="vertical-align: middle;" *ngIf="message.is_self_message">\n <mat-icon>person</mat-icon>\n <img *ngIf="sender_avatar_src" [src]="sender_avatar_src" class="avatar__img">\n </span>\n\n \x3c!--<div class="timeform">--\x3e\n \x3c!--<mat-icon>date</mat-icon> <span class="timestamp">at {{message.created_at | date : \'dd/MM/yyyy\' }}</span>--\x3e\n \x3c!--</div>--\x3e\n </div>\n </div>\n </div>\n </div>\n\n </div>\n\n <div class="input-container">\n <mat-form-field>\n <textarea #msgInput matInput\n cdkTextareaAutosize\n #autosize="cdkTextareaAutosize"\n cdkAutosizeMinRows="2"\n cdkAutosizeMaxRows="5"\n (keyup.enter)="reply()" placeholder="Type a message.." [(ngModel)]="replyContent">\n </textarea>\n </mat-form-field>\n\n <div class="button-wrap">\n <button mat-raised-button\n color="primary"\n class="replyBtn"\n (click)="reply()">\n Send\n </button>\n </div>\n </div>\n\n</div>\n',styles:[':root{--theme-color:#3498db;--window-width:90%}.chatbox{width:var(--window-width,90%);display:flex;flex-direction:column;margin:0 auto;border-radius:5px 5px 0 0;background-color:#fff;box-shadow:0 2px 4px 0 rgba(0,0,0,.2)}.chatbox .chat-header{height:120px;padding:20px;text-align:center;border-radius:5px 5px 0 0;background:#3498db;color:#fff}.chatbox .chat-header .avatar{margin:0 0 10px;width:55px;min-width:55px;height:55px;min-height:55px;text-align:center!important;background-color:#fff!important;vertical-align:middle;color:#000!important}.chatbox .chat-header .name{font-size:20px;font-style:oblique;font-weight:700;display:block}.chatbox .messages{flex:1;overflow:auto;padding:50px 16px 6px;background-color:#fafafa;box-shadow:inset 0 2px 2px rgba(0,0,0,.1)}.chatbox .messages .messages-group{margin-bottom:10px}.chatbox .messages .messages-group .messages-group-label{text-align:center;margin-bottom:10px}.chatbox .messages .messages-group .messages-group-label .hr-sect{display:flex;flex-basis:100%;align-items:center;margin:8px 0}.chatbox .messages .messages-group .messages-group-label .hr-sect::after,.chatbox .messages .messages-group .messages-group-label .hr-sect::before{content:"";flex-grow:1;background:rgba(0,0,0,.1);height:1.5px;font-size:0;line-height:0;margin:0 8px}.chatbox .messages .messages-group .message-div{padding:1px;outline:0}.chatbox .messages .message-item{background-color:#ccc;padding:8px;border-radius:14px;margin-top:0;margin-bottom:0}.chatbox .messages .text-icon{display:flex;flex-direction:row;justify-content:flex-start}.chatbox .messages .self-messages{justify-content:flex-end}.chatbox .messages .self-messages .sender-name{font-size:14px;font-weight:700;margin:2px 5px;text-align:right}.chatbox .messages .self-messages p{color:#fff;background-color:var(--theme-color,#3498db);white-space:pre-line}.chatbox .messages .avatar{margin:0 5px;width:25px;min-width:25px;height:25px;min-height:25px;text-align:center!important;background-color:#fff!important;vertical-align:middle;color:#000!important}.chatbox .input-container{display:flex;flex-direction:row;align-items:center;width:100%;margin:0 auto;background-color:#fff;box-shadow:0 2px 4px 0 rgba(0,0,0,.2);border-radius:0 0 5px 5px;padding:8px;vertical-align:middle;border-top:1px solid #ebebeb}.chatbox .input-container mat-form-field{flex:1}.chatbox .input-container mat-form-field textarea{width:100%}.chatbox .input-container .button-wrap{margin:4px}.chatbox .input-container .button-wrap button{width:70px;margin-left:20px}']}]}],e.ctorParameters=function(){return[{type:h}]},e.propDecorators={msgDivs:[{type:t.ViewChildren,args:["msgDiv"]}],msgsContainer:[{type:t.ViewChild,args:["msgsContainer",{static:!1}]}],chatContainerElement:[{type:t.ViewChild,args:["chatContainer",{static:!1}]}],sender_avatar_src:[{type:t.Input}],recipient_avatar_src:[{type:t.Input}],recipient_display_name:[{type:t.Input}],donor_id:[{type:t.Input}],user_display_name:[{type:t.Input}],user_id:[{type:t.Input}],recipient_user_id:[{type:t.Input}],height:[{type:t.Input}],msgInput:[{type:t.ViewChild,args:["msgInput",{static:!1}]}]},e}();var M={parse:{dateInput:"LL"},display:{dateInput:"LL",monthYearLabel:"MMM YYYY",dateA11yLabel:"LL",monthYearA11yLabel:"MMMM YYYY"}},v=function(){function e(){}return e.decorators=[{type:t.NgModule,args:[{imports:[d.MatDatepickerModule,d.MatDialogModule,u.FlexLayoutModule,s.CommonModule,d.MatCardModule,d.MatProgressSpinnerModule,d.MatMenuModule,d.MatIconModule,d.MatToolbarModule,d.MatButtonModule,d.MatFormFieldModule,d.MatInputModule,d.MatSelectModule,d.MatSortModule,d.MatTableModule,d.MatCheckboxModule,d.MatAutocompleteModule,d.MatNativeDateModule,d.MatPaginatorModule,d.MatSidenavModule,d.MatListModule,g.MatRippleModule,o.BrowserModule,c.BrowserAnimationsModule,d.MatCardModule,d.MatDialogModule,d.MatButtonModule],exports:[d.MatDatepickerModule,d.MatDialogModule,u.FlexLayoutModule,d.MatCardModule,d.MatProgressSpinnerModule,d.MatMenuModule,d.MatIconModule,d.MatToolbarModule,d.MatButtonModule,d.MatFormFieldModule,d.MatInputModule,d.MatSelectModule,d.MatSortModule,d.MatTableModule,d.MatCheckboxModule,d.MatAutocompleteModule,d.MatNativeDateModule,d.MatPaginatorModule,d.MatSidenavModule,d.MatListModule,g.MatRippleModule,d.MatDatepickerModule,d.NativeDateModule],declarations:[],providers:[{provide:g.DateAdapter,useClass:l.MomentDateAdapter,deps:[g.MAT_DATE_LOCALE]},{provide:g.MAT_DATE_FORMATS,useValue:M}]}]}],e}(),_=function(){function e(){}return e.forRoot=function(t){return{ngModule:e,providers:[h,{provide:"config",useValue:t}]}},e.decorators=[{type:t.NgModule,args:[{declarations:[f],imports:[s.CommonModule,o.BrowserModule,v,p.FormsModule],exports:[f],providers:[]}]}],e}();e.ChatBoxComponent=f,e.MessagingModule=_,e.MessagingService=h,e.ɵa=M,e.ɵb=v,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=zoriakinc-messaging.umd.min.js.map