mirror of
https://github.com/moodle/moodle.git
synced 2025-01-18 22:08:20 +01:00
e1b9d5f3cd
Moodle announced that support for IE would be dropped back in August 2020 with Moodle 3.9 but not active steps were taken at that time. That decision was made in MDLSITE-6109 and this particular step was meant to be taken in Moodle 3.10. This is the first step taken to actively drop support for IE. This commit also bumps the browser support pattern from 0.25% to 0.3%. The percentage here includes any browser where at least this percentage of users worldwide may be using a browser. In this case it causes support for Android 4.3-4.4 to be dropped, which relate to Android KitKat (released 2013). This combination of changes means that all of the supported browsers in our compatibility list support modern features including async, for...of, classes, native Promises, and more which has a huge impact on the ease of debugging code, and drastically reduces the minified file size because a number of native Polyfills included by Babel are no longer included.
42 lines
41 KiB
JavaScript
42 lines
41 KiB
JavaScript
/**
|
|
* Controls the conversation page in the message drawer.
|
|
*
|
|
* This function handles all of the user actions that the user can take
|
|
* when interacting with the conversation page.
|
|
*
|
|
* It maintains a view state which is a data representation of the view
|
|
* and only operates on that data.
|
|
*
|
|
* The view state is immutable and should never be modified directly. Instead
|
|
* all changes to the view state should be done using the StateManager which
|
|
* will generate a new version of the view state with the requested changes.
|
|
*
|
|
* After any changes to the view state the module will call the render function
|
|
* to ask the renderer to update the UI.
|
|
*
|
|
* General rules for this module:
|
|
* 1.) Never modify viewState directly. All changes should be via the StateManager.
|
|
* 2.) Call render() with the new state when you want to update the UI
|
|
* 3.) Never modify the UI directly in this module. This module is only concerned
|
|
* with the data in the view state.
|
|
*
|
|
* The general flow for a user interaction will be something like:
|
|
* User interaction: User clicks "confirm block" button to block the other user
|
|
* 1.) This module is hears the click
|
|
* 2.) This module sends a request to the server to block the user
|
|
* 3.) The server responds with the new user profile
|
|
* 4.) This module generates a new state using the StateManager with the updated
|
|
* user profile.
|
|
* 5.) This module asks the Patcher to generate a patch from the current state and
|
|
* the newly generated state. This patch tells the renderer what has changed
|
|
* between the states.
|
|
* 6.) This module gives the Renderer the generated patch. The renderer updates
|
|
* the UI with changes according to the patch.
|
|
*
|
|
* @module core_message/message_drawer_view_conversation
|
|
* @copyright 2018 Ryan Wyllie <ryan@moodle.com>
|
|
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
|
|
*/
|
|
define("core_message/message_drawer_view_conversation",["jquery","core/auto_rows","core/backoff_timer","core/custom_interaction_events","core/notification","core/pending","core/pubsub","core/str","core_message/message_repository","core_message/message_drawer_events","core_message/message_drawer_view_conversation_constants","core_message/message_drawer_view_conversation_patcher","core_message/message_drawer_view_conversation_renderer","core_message/message_drawer_view_conversation_state_manager","core_message/message_drawer_router","core_message/message_drawer_routes","core/emoji/auto_complete","core/emoji/picker"],(function($,AutoRows,BackOffTimer,CustomEvents,Notification,Pending,PubSub,Str,Repository,MessageDrawerEvents,Constants,Patcher,Renderer,StateManager,MessageDrawerRouter,MessageDrawerRoutes,initialiseEmojiAutoComplete,initialiseEmojiPicker){var stateCache={},viewState=null,loadedAllMessages=!1,messagesOffset=0,newMessagesPollTimer=null,isRendering=!1,renderBuffer=[],isResetting=!0,isSendingMessage=!1,isDeletingConversationContent=!1,sendMessageBuffer=[],render=null,renderers=[],NEWEST_FIRST=Constants.NEWEST_MESSAGES_FIRST,LOAD_MESSAGE_LIMIT=Constants.LOAD_MESSAGE_LIMIT,MILLISECONDS_IN_SEC=Constants.MILLISECONDS_IN_SEC,SELECTORS=Constants.SELECTORS,CONVERSATION_TYPES=Constants.CONVERSATION_TYPES,getOtherUserId=function(){if(!viewState||viewState.type==CONVERSATION_TYPES.PUBLIC)return null;var loggedInUserId=viewState.loggedInUserId;if(viewState.type==CONVERSATION_TYPES.SELF)return loggedInUserId;var otherUserIds=Object.keys(viewState.members).filter((function(userId){return loggedInUserId!=userId}));return otherUserIds.length?otherUserIds[0]:null},getMessagesOffset=function(){return messagesOffset},setMessagesOffset=function(value){messagesOffset=value,stateCache[viewState.id].messagesOffset=value},hasLoadedAllMessages=function(){return loadedAllMessages},setLoadedAllMessages=function(value){loadedAllMessages=value,stateCache[viewState.id].loadedAllMessages=value},formatConversationForEvent=function(state){return{id:state.id,name:state.name,subname:state.subname,imageUrl:state.imageUrl,isFavourite:state.isFavourite,isMuted:state.isMuted,type:state.type,totalMemberCount:state.totalMemberCount,loggedInUserId:state.loggedInUserId,messages:state.messages.map((function(message){return $.extend({},message)})),members:Object.keys(state.members).map((function(id){var formattedMember=$.extend({},state.members[id]);return formattedMember.contactrequests=state.members[id].contactrequests.map((function(request){return $.extend({},request)})),formattedMember}))}},updateStateFromConversation=function(conversation,loggedInUserId){var otherUser=null;if(conversation.type==CONVERSATION_TYPES.PRIVATE){var otherUsers=conversation.members.filter((function(member){return member.id!=loggedInUserId}));otherUser=otherUsers.length?otherUsers[0]:null}else conversation.type==CONVERSATION_TYPES.SELF&&(otherUser=conversation.members[0]);var name=conversation.name,imageUrl=conversation.imageurl;conversation.type!=CONVERSATION_TYPES.PUBLIC&&(name=name||otherUser?otherUser.fullname:"",imageUrl=imageUrl||otherUser?otherUser.profileimageurl:"");var newState=StateManager.addMembers(viewState,conversation.members);return newState=StateManager.setName(newState,name),newState=StateManager.setSubname(newState,conversation.subname),newState=StateManager.setType(newState,conversation.type),newState=StateManager.setImageUrl(newState,imageUrl),newState=StateManager.setTotalMemberCount(newState,conversation.membercount),newState=StateManager.setIsFavourite(newState,conversation.isfavourite),newState=StateManager.setIsMuted(newState,conversation.ismuted),newState=StateManager.addMessages(newState,conversation.messages),newState=StateManager.setCanDeleteMessagesForAllUsers(newState,conversation.candeletemessagesforallusers)},loadMessages=function(conversationId,limit,offset,newestFirst,ignoreList,timeFrom){return Repository.getMessages(viewState.loggedInUserId,conversationId,limit?limit+1:limit,offset,newestFirst,timeFrom).then((function(result){return result.id!=viewState.id&&(result.messages=[],result.id in stateCache&&delete stateCache[result.id]),result})).then((function(result){return result.messages.length&&ignoreList.length&&(result.messages=result.messages.filter((function(message){return ignoreList.indexOf(parseInt(message.id,10))<0}))),result})).then((function(result){return limit?(result.messages.length>limit?result.messages=result.messages.slice(0,-1):setLoadedAllMessages(!0),result):result})).then((function(result){var membersToAdd=result.members.filter((function(member){return!(member.id in viewState.members)})),newState=StateManager.addMembers(viewState,membersToAdd);return newState=StateManager.addMessages(newState,result.messages),newState=StateManager.setLoadingMessages(newState,!1),render(newState).then((function(){return result}))})).catch((function(error){var newState=StateManager.setLoadingMessages(viewState,!1);throw render(newState),error}))},markConversationAsRead=function(conversationId){var loggedInUserId=viewState.loggedInUserId,pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead");return Repository.markAllConversationMessagesAsRead(loggedInUserId,conversationId).then((function(){var newState=StateManager.markMessagesAsRead(viewState,viewState.messages);return PubSub.publish(MessageDrawerEvents.CONVERSATION_READ,conversationId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestBlockUser=function(userId){cancelRequest(userId);var newState=StateManager.addPendingBlockUsersById(viewState,[userId]);render(newState)},blockUser=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:blockUser");return render(newState),Repository.blockUser(viewState.loggedInUserId,userId).then((function(profile){var newState=StateManager.addMembers(viewState,[profile]);return newState=StateManager.removePendingBlockUsersById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_BLOCKED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestUnblockUser=function(userId){cancelRequest(userId);var newState=StateManager.addPendingUnblockUsersById(viewState,[userId]);render(newState)},unblockUser=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:unblockUser");return render(newState),Repository.unblockUser(viewState.loggedInUserId,userId).then((function(profile){var newState=StateManager.addMembers(viewState,[profile]);return newState=StateManager.removePendingUnblockUsersById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_UNBLOCKED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestRemoveContact=function(userId){cancelRequest(userId);var newState=StateManager.addPendingRemoveContactsById(viewState,[userId]);render(newState)},removeContact=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:removeContact");return render(newState),Repository.deleteContacts(viewState.loggedInUserId,[userId]).then((function(profiles){var newState=StateManager.addMembers(viewState,profiles);return newState=StateManager.removePendingRemoveContactsById(newState,[userId]),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONTACT_REMOVED,userId),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestAddContact=function(userId){cancelRequest(userId);var newState=StateManager.addPendingAddContactsById(viewState,[userId]);render(newState)},addContact=function(userId){var newState=StateManager.setLoadingConfirmAction(viewState,!0),pendingPromise=new Pending("core_message/message_drawer_view_conversation:addContactRequests");return render(newState),Repository.createContactRequest(viewState.loggedInUserId,userId).then((function(response){if(!response.request)throw new Error(response.warnings[0].message);return response.request})).then((function(request){var newState=StateManager.removePendingAddContactsById(viewState,[userId]);return newState=StateManager.addContactRequests(newState,[request]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},requestDeleteSelectedMessages=function(userId){var selectedMessageIds=viewState.selectedMessageIds;cancelRequest(userId);var newState=StateManager.addPendingDeleteMessagesById(viewState,selectedMessageIds);render(newState)},deleteSelectedMessages=function(){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:deleteSelectedMessages"),messageIds=viewState.pendingDeleteMessageIds,sentMessages=viewState.messages.filter((function(message){return messageIds.indexOf(message.id)>=0&&("sent"==message.sendState||null===message.sendState)})),newState=StateManager.setLoadingConfirmAction(viewState,!0);render(newState);var deleteMessagesPromise=$.Deferred().resolve().promise();if(sentMessages.length){var sentMessageIds=sentMessages.map((function(message){return message.id}));deleteMessagesPromise=newState.deleteMessagesForAllUsers?Repository.deleteMessagesForAllUsers(viewState.loggedInUserId,sentMessageIds):Repository.deleteMessages(viewState.loggedInUserId,sentMessageIds)}return isDeletingConversationContent=!0,newMessagesPollTimer&&newMessagesPollTimer.stop(),deleteMessagesPromise.then((function(){var newState=StateManager.removeMessagesById(viewState,messageIds);newState=StateManager.removePendingDeleteMessagesById(newState,messageIds),newState=StateManager.removeSelectedMessagesById(newState,messageIds),newState=StateManager.setLoadingConfirmAction(newState,!1),newState=StateManager.setDeleteMessagesForAllUsers(newState,!1);var prevLastMessage=viewState.messages[viewState.messages.length-1],newLastMessage=newState.messages.length?newState.messages[newState.messages.length-1]:null;if(newLastMessage&&newLastMessage.id!=prevLastMessage.id){var conversation=formatConversationForEvent(newState);PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation)}else newState.messages.length||PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED,newState.id);return isDeletingConversationContent=!1,render(newState)})).then((function(result){return pendingPromise.resolve(),result})).catch(Notification.exception)},requestDeleteConversation=function(userId){cancelRequest(userId);var newState=StateManager.setPendingDeleteConversation(viewState,!0);render(newState)},deleteConversation=function(){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead"),newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),isDeletingConversationContent=!0,newMessagesPollTimer&&newMessagesPollTimer.stop(),Repository.deleteConversation(viewState.loggedInUserId,viewState.id).then((function(){var newState=StateManager.removeMessages(viewState,viewState.messages);return newState=StateManager.removeSelectedMessagesById(newState,viewState.selectedMessageIds),newState=StateManager.setPendingDeleteConversation(newState,!1),newState=StateManager.setLoadingConfirmAction(newState,!1),PubSub.publish(MessageDrawerEvents.CONVERSATION_DELETED,newState.id),isDeletingConversationContent=!1,render(newState)})).then((function(result){return pendingPromise.resolve(),result}))},cancelRequest=function(userId){var pendingDeleteMessageIds=viewState.pendingDeleteMessageIds,newState=StateManager.removePendingAddContactsById(viewState,[userId]);newState=StateManager.removePendingRemoveContactsById(newState,[userId]),newState=StateManager.removePendingUnblockUsersById(newState,[userId]),newState=StateManager.removePendingBlockUsersById(newState,[userId]),newState=StateManager.removePendingDeleteMessagesById(newState,pendingDeleteMessageIds),newState=StateManager.setPendingDeleteConversation(newState,!1),newState=StateManager.setDeleteMessagesForAllUsers(newState,!1),render(newState)},acceptContactRequest=function(userId){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:acceptContactRequest"),loggedInUserId=viewState.loggedInUserId,requests=viewState.members[userId].contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId})),request=requests[0],newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),Repository.acceptContactRequest(userId,loggedInUserId).then((function(profile){var newState=StateManager.removeContactRequests(viewState,[request]);return newState=StateManager.addMembers(viewState,[profile]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(){PubSub.publish(MessageDrawerEvents.CONTACT_ADDED,viewState.members[userId]),PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_ACCEPTED,request)})).then((function(result){return pendingPromise.resolve(),result}))},declineContactRequest=function(userId){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:declineContactRequest"),loggedInUserId=viewState.loggedInUserId,requests=viewState.members[userId].contactrequests.filter((function(request){return request.requesteduserid==loggedInUserId})),request=requests[0],newState=StateManager.setLoadingConfirmAction(viewState,!0);return render(newState),Repository.declineContactRequest(userId,loggedInUserId).then((function(profile){var newState=StateManager.removeContactRequests(viewState,[request]);return newState=StateManager.addMembers(viewState,[profile]),newState=StateManager.setLoadingConfirmAction(newState,!1),render(newState)})).then((function(){PubSub.publish(MessageDrawerEvents.CONTACT_REQUEST_DECLINED,request)})).then((function(result){return pendingPromise.resolve(),result}))},processSendMessageBuffer=function(){if(!isSendingMessage&&sendMessageBuffer.length){var pendingPromise=new Pending("core_message/message_drawer_view_conversation:processSendMessageBuffer");isSendingMessage=!0;var messagesToSend=sendMessageBuffer.slice();sendMessageBuffer=[];var conversationId=viewState.id,newConversationId=null,messagesText=messagesToSend.map((function(message){return message.text})),messageIds=messagesToSend.map((function(message){return message.id})),sendMessagePromise=null,newCanDeleteMessagesForAllUsers=null;if(conversationId||viewState.type==CONVERSATION_TYPES.PUBLIC)sendMessagePromise=Repository.sendMessagesToConversation(conversationId,messagesText);else{var otherUserId=getOtherUserId();sendMessagePromise=Repository.sendMessagesToUser(otherUserId,messagesText).then((function(messages){return messages.length&&(newConversationId=parseInt(messages[0].conversationid,10),newCanDeleteMessagesForAllUsers=messages[0].candeletemessagesforallusers),messages}))}sendMessagePromise.then((function(messages){var newMessageIds=messages.map((function(message){return message.id})),data=[],selectedToRemove=[],selectedToAdd=[];messagesToSend.forEach((function(oldMessage,index){var newMessage=messages[index];data.push([oldMessage,newMessage]),viewState.selectedMessageIds.indexOf(oldMessage.id)>=0&&(selectedToRemove.push(oldMessage.id),selectedToAdd.push(newMessage.id))}));var newState=StateManager.updateMessages(viewState,data);newState=StateManager.setMessagesSendSuccessById(newState,newMessageIds),selectedToRemove.length&&(newState=StateManager.removeSelectedMessagesById(newState,selectedToRemove)),selectedToAdd.length&&(newState=StateManager.addSelectedMessagesById(newState,selectedToAdd));var conversation=formatConversationForEvent(newState);newState.id||(newState=StateManager.setId(newState,newConversationId),conversation.id=newConversationId,resetMessagePollTimer(newConversationId),PubSub.publish(MessageDrawerEvents.CONVERSATION_CREATED,conversation),newState=StateManager.setCanDeleteMessagesForAllUsers(newState,newCanDeleteMessagesForAllUsers)),render(newState),isSendingMessage=!1,processSendMessageBuffer(),PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation)})).then((function(result){return pendingPromise.resolve(),result})).catch((function(e){var errorMessage;errorMessage=e.message?$.Deferred().resolve(e.message).promise():Str.get_string("unknownerror","core");var handleFailedMessages=function(errorMessage){var newState=StateManager.setMessagesSendFailById(viewState,messageIds,errorMessage);render(newState),isSendingMessage=!1,processSendMessageBuffer()};errorMessage.then(handleFailedMessages).then((function(result){return pendingPromise.resolve(),result})).catch((function(e){var finalError=e.message||"Something went wrong!";handleFailedMessages(finalError)}))}))}};const previewText=function(text){let plaintext=text.replace(/<style([\s\S]*?)<\/style>/gi,"");return plaintext=plaintext.replace(/<script([\s\S]*?)<\/script>/gi,""),plaintext=plaintext.replace(/<\/div>/gi,"\n"),plaintext=plaintext.replace(/<\/li>/gi,"\n"),plaintext=plaintext.replace(/<li>/gi," * "),plaintext=plaintext.replace(/<\/ul>/gi,"\n"),plaintext=plaintext.replace(/<\/p>/gi,"\n"),plaintext=plaintext.replace(/<br[^>]*>/gi,"\n"),plaintext=plaintext.replace(/<[^>]+>/gi,""),plaintext=plaintext.replace(/\n+/gi,"\n"),plaintext.replace(/\n/gi,"<br>")};var processRenderBuffer=function(header,body,footer){if(!isRendering&&renderBuffer.length){isRendering=!0;var renderable=renderBuffer.shift(),renderPromises=renderers.map((function(renderFunc){return renderFunc(renderable.patch)}));$.when.apply(null,renderPromises).then((function(){isRendering=!1,renderable.deferred.resolve(!0),processRenderBuffer(header,body,footer)})).catch((function(error){isRendering=!1,renderable.deferred.reject(error),Notification.exception(error)}))}},generateConfirmActionHandler=function(actionCallback){return function(e,data){if(!viewState.loadingConfirmAction){actionCallback(getOtherUserId());var newState=StateManager.setLoadingConfirmAction(viewState,!1);render(newState)}data.originalEvent.preventDefault()}},handleSendMessage=function(e,data){var textArea=$(e.target).closest(SELECTORS.FOOTER_CONTAINER).find(SELECTORS.MESSAGE_TEXT_AREA),text=textArea.val().trim();""!==text&&(!function(text){var id="temp"+Date.now();let loadingmessage={id:id,useridfrom:viewState.loggedInUserId,text:previewText(text),timecreated:null};var newState=StateManager.addMessages(viewState,[loadingmessage]);render(newState);var message={id:id,useridfrom:viewState.loggedInUserId,text:text,timecreated:null};sendMessageBuffer.push(message),processSendMessageBuffer()}(text),textArea.val(""),textArea.focus()),data.originalEvent.preventDefault()},handleSelectMessage=function(e,data){var selection=window.getSelection(),target=$(e.target);""==selection.toString()&&(target.is("a")||(!function(messageId){var newState=viewState;newState=viewState.selectedMessageIds.indexOf(messageId)>-1?StateManager.removeSelectedMessagesById(viewState,[messageId]):StateManager.addSelectedMessagesById(viewState,[messageId]),render(newState)}(target.closest(SELECTORS.MESSAGE).attr("data-message-id")),data.originalEvent.preventDefault()))},handleRetrySendMessage=function(e,data){var messageId=$(e.target).closest(SELECTORS.MESSAGE).attr("data-message-id"),messages=viewState.messages.filter((function(message){return message.id==messageId})),message=messages.length?messages[0]:null;message&&function(message){var newState=StateManager.setMessagesSendPendingById(viewState,[message.id]);render(newState),sendMessageBuffer.push(message),processSendMessageBuffer()}(message),data.originalEvent.preventDefault(),data.originalEvent.stopPropagation(),e.stopPropagation()},handleCancelEditMode=function(e,data){!function(){cancelRequest(getOtherUserId());var newState=StateManager.removeSelectedMessagesById(viewState,viewState.selectedMessageIds);render(newState)}(),data.originalEvent.preventDefault()},generateHandleViewContact=function(namespace){return function(e,data){var otherUserId=getOtherUserId(),otherUser=viewState.members[otherUserId];MessageDrawerRouter.go(namespace,MessageDrawerRoutes.VIEW_CONTACT,otherUser),data.originalEvent.preventDefault()}},handleSetFavourite=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:setFavourite"),Repository.setFavouriteConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsFavourite(viewState,!0);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_SET_FAVOURITE,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleUnsetFavourite=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:unsetFavourite"),Repository.unsetFavouriteConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsFavourite(viewState,!1);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_UNSET_FAVOURITE,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleSetMuted=function(e,data){var userId,conversationId,pendingPromise;(userId=viewState.loggedInUserId,conversationId=viewState.id,pendingPromise=new Pending("core_message/message_drawer_view_conversation:markConversationAsRead"),Repository.setMutedConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsMuted(viewState,!0);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_SET_MUTED,formatConversationForEvent(viewState))})).then((function(result){return pendingPromise.resolve(),result}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleUnsetMuted=function(e,data){var userId,conversationId;(userId=viewState.loggedInUserId,conversationId=viewState.id,Repository.unsetMutedConversations(userId,[conversationId]).then((function(){var newState=StateManager.setIsMuted(viewState,!1);return render(newState)})).then((function(){return PubSub.publish(MessageDrawerEvents.CONVERSATION_UNSET_MUTED,formatConversationForEvent(viewState))}))).catch(Notification.exception),data.originalEvent.preventDefault()},handleDeleteMessagesForAllUsersToggle=function(e){var newValue=$(e.target).prop("checked"),newState=StateManager.setDeleteMessagesForAllUsers(viewState,newValue);render(newState)},generateHandleViewGroupInfo=function(namespace){return function(e,data){MessageDrawerRouter.go(namespace,MessageDrawerRoutes.VIEW_GROUP_INFO,{id:viewState.id,name:viewState.name,subname:viewState.subname,imageUrl:viewState.imageUrl,totalMemberCount:viewState.totalMemberCount},viewState.loggedInUserId),data.originalEvent.preventDefault()}},handleToggleEmojiPicker=function(e,data){var newState=StateManager.setShowEmojiPicker(viewState,!viewState.showEmojiPicker);render(newState),data.originalEvent.preventDefault()},handleCloseEmojiPicker=function(e){var target=$(e.target);if(viewState.showEmojiPicker&&!target.closest(SELECTORS.EMOJI_PICKER_CONTAINER).length&&!target.closest(SELECTORS.TOGGLE_EMOJI_PICKER_BUTTON).length){var newState=StateManager.setShowEmojiPicker(viewState,!1);render(newState)}},registerEventListeners=function(namespace,header,body,footer){var isLoadingMoreMessages=!1,messagesContainer=function(body){return body.find(SELECTORS.MESSAGES_CONTAINER)}(body),emojiPickerElement=footer.find(SELECTORS.EMOJI_PICKER),emojiAutoCompleteContainer=footer.find(SELECTORS.EMOJI_AUTO_COMPLETE_CONTAINER),messageTextArea=footer.find(SELECTORS.MESSAGE_TEXT_AREA),headerActivateHandlers=[[SELECTORS.ACTION_REQUEST_BLOCK,generateConfirmActionHandler(requestBlockUser)],[SELECTORS.ACTION_REQUEST_UNBLOCK,generateConfirmActionHandler(requestUnblockUser)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_REQUEST_REMOVE_CONTACT,generateConfirmActionHandler(requestRemoveContact)],[SELECTORS.ACTION_REQUEST_DELETE_CONVERSATION,generateConfirmActionHandler(requestDeleteConversation)],[SELECTORS.ACTION_CANCEL_EDIT_MODE,handleCancelEditMode],[SELECTORS.ACTION_VIEW_CONTACT,generateHandleViewContact(namespace)],[SELECTORS.ACTION_VIEW_GROUP_INFO,generateHandleViewGroupInfo(namespace)],[SELECTORS.ACTION_CONFIRM_FAVOURITE,handleSetFavourite],[SELECTORS.ACTION_CONFIRM_MUTE,handleSetMuted],[SELECTORS.ACTION_CONFIRM_UNFAVOURITE,handleUnsetFavourite],[SELECTORS.ACTION_CONFIRM_UNMUTE,handleUnsetMuted]],bodyActivateHandlers=[[SELECTORS.ACTION_CANCEL_CONFIRM,generateConfirmActionHandler(cancelRequest)],[SELECTORS.ACTION_CONFIRM_BLOCK,generateConfirmActionHandler(blockUser)],[SELECTORS.ACTION_CONFIRM_UNBLOCK,generateConfirmActionHandler(unblockUser)],[SELECTORS.ACTION_CONFIRM_ADD_CONTACT,generateConfirmActionHandler(addContact)],[SELECTORS.ACTION_CONFIRM_REMOVE_CONTACT,generateConfirmActionHandler(removeContact)],[SELECTORS.ACTION_CONFIRM_DELETE_SELECTED_MESSAGES,generateConfirmActionHandler(deleteSelectedMessages)],[SELECTORS.ACTION_CONFIRM_DELETE_CONVERSATION,generateConfirmActionHandler(deleteConversation)],[SELECTORS.ACTION_OKAY_CONFIRM,generateConfirmActionHandler(cancelRequest)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_ACCEPT_CONTACT_REQUEST,generateConfirmActionHandler(acceptContactRequest)],[SELECTORS.ACTION_DECLINE_CONTACT_REQUEST,generateConfirmActionHandler(declineContactRequest)],[SELECTORS.MESSAGE,handleSelectMessage],[SELECTORS.DELETE_MESSAGES_FOR_ALL_USERS_TOGGLE,handleDeleteMessagesForAllUsersToggle],[SELECTORS.RETRY_SEND,handleRetrySendMessage]],footerActivateHandlers=[[SELECTORS.SEND_MESSAGE_BUTTON,handleSendMessage],[SELECTORS.TOGGLE_EMOJI_PICKER_BUTTON,handleToggleEmojiPicker],[SELECTORS.ACTION_REQUEST_DELETE_SELECTED_MESSAGES,generateConfirmActionHandler(requestDeleteSelectedMessages)],[SELECTORS.ACTION_REQUEST_ADD_CONTACT,generateConfirmActionHandler(requestAddContact)],[SELECTORS.ACTION_REQUEST_UNBLOCK,generateConfirmActionHandler(requestUnblockUser)]];AutoRows.init(footer),emojiAutoCompleteContainer.length&&initialiseEmojiAutoComplete(emojiAutoCompleteContainer[0],messageTextArea[0],(function(hasSuggestions){var newState=StateManager.setShowEmojiAutoComplete(viewState,hasSuggestions);render(newState)}),(function(emoji){var newState=StateManager.setShowEmojiAutoComplete(viewState,!1);render(newState),messageTextArea.focus();var cursorPos=messageTextArea.prop("selectionStart"),currentText=messageTextArea.val(),textBefore=currentText.substring(0,cursorPos).replace(/\S*$/,""),textAfter=currentText.substring(cursorPos).replace(/^\S*/,"");messageTextArea.val(textBefore+emoji+textAfter),messageTextArea.prop("selectionStart",textBefore.length+emoji.length),messageTextArea.prop("selectionEnd",textBefore.length+emoji.length)})),emojiPickerElement.length&&initialiseEmojiPicker(emojiPickerElement[0],(function(emoji){var newState=StateManager.setShowEmojiPicker(viewState,!viewState.showEmojiPicker);render(newState),messageTextArea.focus();var cursorPos=messageTextArea.prop("selectionStart"),currentText=messageTextArea.val(),textBefore=currentText.substring(0,cursorPos),textAfter=currentText.substring(cursorPos,currentText.length);messageTextArea.val(textBefore+emoji+textAfter),messageTextArea.prop("selectionStart",cursorPos+emoji.length),messageTextArea.prop("selectionEnd",cursorPos+emoji.length)})),CustomEvents.define(header,[CustomEvents.events.activate]),CustomEvents.define(body,[CustomEvents.events.activate]),CustomEvents.define(footer,[CustomEvents.events.activate,CustomEvents.events.enter,CustomEvents.events.escape]),CustomEvents.define(messagesContainer,[CustomEvents.events.scrollTop,CustomEvents.events.scrollLock]),messagesContainer.on(CustomEvents.events.scrollTop,(function(e,data){var hasMembers=Object.keys(viewState.members).length>1;if(!isResetting&&!isLoadingMoreMessages&&!hasLoadedAllMessages()&&hasMembers){isLoadingMoreMessages=!0;var newState=StateManager.setLoadingMessages(viewState,!0);render(newState),loadMessages(viewState.id,LOAD_MESSAGE_LIMIT,getMessagesOffset(),NEWEST_FIRST,[]).then((function(){isLoadingMoreMessages=!1,setMessagesOffset(getMessagesOffset()+LOAD_MESSAGE_LIMIT)})).catch((function(error){isLoadingMoreMessages=!1,Notification.exception(error)}))}data.originalEvent.preventDefault()})),headerActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];header.on(CustomEvents.events.activate,selector,handlerFunction)})),bodyActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];body.on(CustomEvents.events.activate,selector,handlerFunction)})),footerActivateHandlers.forEach((function(handler){var selector=handler[0],handlerFunction=handler[1];footer.on(CustomEvents.events.activate,selector,handlerFunction)})),footer.on(CustomEvents.events.enter,SELECTORS.MESSAGE_TEXT_AREA,(function(e,data){var enterToSend=footer.attr("data-enter-to-send");enterToSend&&"false"!=enterToSend&&"0"!=enterToSend&&handleSendMessage(e,data)})),footer.on(CustomEvents.events.escape,SELECTORS.EMOJI_PICKER_CONTAINER,handleToggleEmojiPicker),$(document.body).on("click",handleCloseEmojiPicker),PubSub.subscribe(MessageDrawerEvents.ROUTE_CHANGED,(function(newRouteData){newMessagesPollTimer&&newRouteData.route!=MessageDrawerRoutes.VIEW_CONVERSATION&&newMessagesPollTimer.stop()}))},resetMessagePollTimer=function(conversationId){newMessagesPollTimer&&newMessagesPollTimer.stop(),newMessagesPollTimer=new BackOffTimer(function(conversationId,newestFirst){return function(){var messages=viewState.messages,mostRecentMessage=messages.length?messages[messages.length-1]:null,lastTimeCreated=mostRecentMessage?mostRecentMessage.timeCreated:null;if(lastTimeCreated&&!isResetting&&!isSendingMessage&&!isDeletingConversationContent){for(var ignoreMessageIds=[],i=messages.length-1;i>=0;i--){var message=messages[i];if(message.timeCreated!==lastTimeCreated)break;ignoreMessageIds.push(message.id)}return loadMessages(conversationId,0,0,newestFirst,ignoreMessageIds,lastTimeCreated).then((function(result){if(result.messages.length){newMessagesPollTimer.restart();var conversation=formatConversationForEvent(viewState);return PubSub.publish(MessageDrawerEvents.CONVERSATION_NEW_LAST_MESSAGE,conversation),markConversationAsRead(conversationId)}return result}))}return $.Deferred().resolve().promise()}}(conversationId,NEWEST_FIRST),BackOffTimer.getIncrementalCallback(viewState.messagePollMin*MILLISECONDS_IN_SEC,MILLISECONDS_IN_SEC,viewState.messagePollMax*MILLISECONDS_IN_SEC,viewState.messagePollAfterMax*MILLISECONDS_IN_SEC)),newMessagesPollTimer.start()},resetState=function(body,conversationId,loggedInUserProfile){newMessagesPollTimer&&newMessagesPollTimer.stop(),loadedAllMessages=!1,messagesOffset=0,newMessagesPollTimer=null,isRendering=!1,renderBuffer=[],isResetting=!0,isSendingMessage=!1,isDeletingConversationContent=!1,sendMessageBuffer=[];var loggedInUserId=loggedInUserProfile.id,midnight=parseInt(body.attr("data-midnight"),10),messagePollMin=parseInt(body.attr("data-message-poll-min"),10),messagePollMax=parseInt(body.attr("data-message-poll-max"),10),messagePollAfterMax=parseInt(body.attr("data-message-poll-after-max"),10),initialState=StateManager.buildInitialState(midnight,loggedInUserId,conversationId,messagePollMin,messagePollMax,messagePollAfterMax);viewState||(viewState=initialState),render(initialState)},resetNoConversation=function(body,loggedInUserProfile,otherUserId){resetState(body,null,loggedInUserProfile);return(loggedInUserProfile.id!=otherUserId?Repository.getConversationBetweenUsers(loggedInUserProfile.id,otherUserId,!0,!0,0,0,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST):Repository.getSelfConversation(loggedInUserProfile.id,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST)).then((function(conversation){return resetByConversation(body,conversation,loggedInUserProfile)})).catch((function(){return function(loggedInUserProfile,otherUserId){var loggedInUserId=loggedInUserProfile.id,conversationType=loggedInUserId==otherUserId?CONVERSATION_TYPES.SELF:CONVERSATION_TYPES.PRIVATE,newState=StateManager.setLoadingMembers(viewState,!0);return newState=StateManager.setLoadingMessages(newState,!0),render(newState),Repository.getMemberInfo(loggedInUserId,[otherUserId],!0,!0).then((function(profiles){if(profiles.length)return profiles[0];throw new Error("Unable to load other user profile")})).then((function(profile){var members=conversationType==CONVERSATION_TYPES.SELF?[profile]:[profile,loggedInUserProfile],newState=StateManager.addMembers(viewState,members);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setName(newState,profile.fullname),newState=StateManager.setType(newState,conversationType),newState=StateManager.setImageUrl(newState,profile.profileimageurl),newState=StateManager.setTotalMemberCount(newState,members.length),render(newState),profile})).catch((function(error){var newState=StateManager.setLoadingMembers(viewState,!1);render(newState),Notification.exception(error)}))}(loggedInUserProfile,otherUserId)}))},resetById=function(body,conversationId,loggedInUserProfile){var cache=null;conversationId in stateCache&&(cache=stateCache[conversationId]),resetState(body,conversationId,loggedInUserProfile);var promise=$.Deferred().resolve({}).promise();if(cache){var newState=cache.state;newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setLoadingMembers(newState,!1),setMessagesOffset(cache.messagesOffset),setLoadedAllMessages(cache.loadedAllMessages),render(newState)}else promise=function(conversationId,loggedInUserProfile,messageLimit,messageOffset,newestFirst){var loggedInUserId=loggedInUserProfile.id,newState=StateManager.setLoadingMembers(viewState,!0);return newState=StateManager.setLoadingMessages(newState,!0),render(newState),Repository.getConversation(loggedInUserId,conversationId,!0,!0,0,0,messageLimit+1,messageOffset,newestFirst).then((function(conversation){return conversation.messages.length>messageLimit?conversation.messages=conversation.messages.slice(1):setLoadedAllMessages(!0),setMessagesOffset(messageOffset+messageLimit),conversation})).then((function(conversation){conversation.members.filter((function(member){return member.id==loggedInUserProfile.id})).length<1&&(conversation.members=conversation.members.concat([loggedInUserProfile]));var newState=updateStateFromConversation(conversation,loggedInUserProfile.id);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!1),render(newState).then((function(){return conversation}))})).then((function(){return markConversationAsRead(conversationId)})).catch((function(error){var newState=StateManager.setLoadingMembers(viewState,!1);newState=StateManager.setLoadingMessages(newState,!1),render(newState),Notification.exception(error)}))}(conversationId,loggedInUserProfile,LOAD_MESSAGE_LIMIT,0,NEWEST_FIRST);return promise.then((function(){return resetMessagePollTimer(conversationId)}))},resetByConversation=function(body,conversation,loggedInUserProfile){var cache=null;conversation.id in stateCache&&(cache=stateCache[conversation.id]),resetState(body,conversation.id,loggedInUserProfile);var promise=$.Deferred().resolve({}).promise();if(cache){var newState=cache.state;newState=StateManager.setLoadingMessages(newState,!1),newState=StateManager.setLoadingMembers(newState,!1),setMessagesOffset(cache.messagesOffset),setLoadedAllMessages(cache.loadedAllMessages),render(newState)}else promise=function(conversation,loggedInUserProfile,messageLimit,newestFirst){conversation.members.filter((function(member){return member.id==loggedInUserProfile.id})).length<1&&(conversation.members=conversation.members.concat([loggedInUserProfile]));var messageCount=conversation.messages.length,hasLoadedEnoughMessages=messageCount>=messageLimit,newState=updateStateFromConversation(conversation,loggedInUserProfile.id);return newState=StateManager.setLoadingMembers(newState,!1),newState=StateManager.setLoadingMessages(newState,!hasLoadedEnoughMessages),render(newState).then((function(){return hasLoadedEnoughMessages?{messages:conversation.messages}:loadMessages(conversation.id,messageLimit,messageCount,newestFirst,[])})).then((function(){var messages=viewState.messages;return setMessagesOffset(messages.length),markConversationAsRead(viewState.id),messages})).catch(Notification.exception)}(conversation,loggedInUserProfile,LOAD_MESSAGE_LIMIT,NEWEST_FIRST);return promise.then((function(){return resetMessagePollTimer(conversation.id)}))};return{show:function(namespace,header,body,footer,conversationOrId,action,otherUserId){var userId,conversation=null,conversationId=null;conversationOrId&&null!==conversationOrId&&"object"==typeof conversationOrId?(conversation=conversationOrId,conversationId=parseInt(conversation.id,10)):(conversation=null,conversationId=parseInt(conversationOrId,10),conversationId=isNaN(conversationId)?null:conversationId),!conversationId&&action&&otherUserId&&(userId=otherUserId,conversationId=Object.keys(stateCache).reduce((function(carry,id){if(!carry){var state=stateCache[id].state;state.type!=CONVERSATION_TYPES.PUBLIC&&userId in state.members&&(carry=state.id)}return carry}),null));var isNewConversation=!viewState||viewState.id!=conversationId||otherUserId&&otherUserId!=getOtherUserId();if(body.attr("data-init")||(render=function(header,body,footer,isNewConversation){var rendererFunc=function(patch){return Renderer.render(header,body,footer,patch)};if(!isNewConversation){var initialState=StateManager.buildInitialState(viewState.midnight,viewState.loggedInUserId,viewState.id);rendererFunc(Patcher.buildPatch(initialState,viewState))}return renderers.push(rendererFunc),function(newState){var patch=Patcher.buildPatch(viewState,newState),deferred=$.Deferred();return Object.keys(patch).length?renderBuffer.push({patch:patch,deferred:deferred}):deferred.resolve(!0),viewState=newState,newState.id&&(stateCache[newState.id]={state:newState,messagesOffset:getMessagesOffset(),loadedAllMessages:hasLoadedAllMessages()}),processRenderBuffer(header,body,footer),deferred.promise()}}(header,body,footer,isNewConversation),registerEventListeners(namespace,header,body,footer),body.attr("data-init",!0)),isNewConversation){var loggedInUserProfile=function(body){return{id:parseInt(body.attr("data-user-id"),10),fullname:null,profileimageurl:null,profileimageurlsmall:null,isonline:null,showonlinestatus:null,isblocked:null,iscontact:null,isdeleted:null,canmessage:null,canmessageevenifblocked:null,requirescontact:null,contactrequests:[]}}(body);return(conversation?resetByConversation(body,conversation,loggedInUserProfile,otherUserId):conversationId?resetById(body,conversationId,loggedInUserProfile):resetNoConversation(body,loggedInUserProfile,otherUserId)).then((function(){isResetting=!1,header.find(Constants.SELECTORS.CAN_RECEIVE_FOCUS).first().focus()})).catch((function(error){isResetting=!1,Notification.exception(error)}))}if(resetMessagePollTimer(conversationId),viewState.type==CONVERSATION_TYPES.PRIVATE&&action){var currentOtherUserId=getOtherUserId();switch(action){case"block":return requestBlockUser(currentOtherUserId);case"unblock":return requestUnblockUser(currentOtherUserId);case"add-contact":return requestAddContact(currentOtherUserId);case"remove-contact":return requestRemoveContact(currentOtherUserId)}}return $.Deferred().resolve().promise()},description:function(){return Str.get_string("messagedrawerviewconversation","core_message",viewState.name)}}}));
|
|
|
|
//# sourceMappingURL=message_drawer_view_conversation.min.js.map
|