@cometchat/chat-uikit-angular
Version:
Ready-to-use Chat UI Components for Angular (JavaScript/Web)
1,096 lines (1,095 loc) • 725 kB
JavaScript
import { ChangeDetectionStrategy, Component, Input, ViewChild, ViewChildren, } from "@angular/core";
import { AvatarStyle, CallscreenStyle, CheckboxStyle, DateStyle, DropdownStyle, InputStyle, LabelStyle, ListItemStyle, QuickViewStyle, RadioButtonStyle, ReceiptStyle, SingleSelectStyle, } from "@cometchat/uikit-elements";
import { CalendarStyle, CallingDetailsUtils, CardBubbleStyle, CollaborativeDocumentConstants, CollaborativeWhiteboardConstants, CometChatSoundManager, TimeSlotStyle, CometChatUIKitUtility, FormBubbleStyle, InteractiveMessageUtils, LinkPreviewConstants, MessageInformationConfiguration, MessageListStyle, MessageReceiptUtils, MessageTranslationConstants, MessageTranslationStyle, SchedulerBubbleStyle, SmartRepliesConstants, ThumbnailGenerationConstants, ReactionsStyle, ReactionListConfiguration, ReactionInfoConfiguration, ReactionListStyle, ReactionInfoStyle, ReactionsConfiguration, CometChatUrlsFormatter, CometChatMentionsFormatter, CometChatUIKitLoginListener, StorageUtils, } from "@cometchat/uikit-shared";
import { CometChatCallEvents, CometChatGroupEvents, CometChatMessageEvents, CometChatTheme, CometChatUIEvents, CometChatUIKitConstants, DatePatterns, DocumentIconAlignment, MessageBubbleAlignment, MessageListAlignment, MessageStatus, Placement, States, TimestampAlignment, fontHelper, localize, } from "@cometchat/uikit-resources";
import { CometChatUIKitCalls, LinkPreviewStyle, StickersConstants, } from "@cometchat/uikit-shared";
import { ChatConfigurator } from "../../Shared/Framework/ChatConfigurator";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { CometChatException } from "../../Shared/Utils/ComeChatException";
import { CometChatUIKit } from "../../Shared/CometChatUIkit/CometChatUIKit";
import * as i0 from "@angular/core";
import * as i1 from "../../CometChatTheme.service";
import * as i2 from "../../CometChatMessageBubble/cometchat-message-bubble/cometchat-message-bubble.component";
import * as i3 from "../../Calls/CometChatOngoingCall/cometchat-ongoing-call/cometchat-ongoing-call.component";
import * as i4 from "../../CometChatMessageInformation/cometchat-message-information/cometchat-message-information.component";
import * as i5 from "@angular/common";
/**
*
* CometChatMessageList is a wrapper component for messageBubble
*
* @version 1.0.0
* @author CometChatTeam
* @copyright © 2022 CometChat Inc.
*
*/
export class CometChatMessageListComponent {
constructor(ngZone, ref, themeService) {
this.ngZone = ngZone;
this.ref = ref;
this.themeService = themeService;
this.hideError = false;
this.hideDateSeparator = false;
this.errorStateText = localize("SOMETHING_WRONG");
this.emptyStateText = localize("NO_MESSAGES_FOUND");
this.loadingIconURL = "assets/Spinner.svg";
/**
* @deprecated
*
* This property is deprecated as of version 4.3.16 due to newer property 'hideReceipt'. It will be removed in subsequent versions.
*/
this.disableReceipt = false;
this.hideReceipt = false;
this.disableSoundForMessages = false;
this.customSoundForMessages = "";
this.readIcon = "assets/message-read.svg";
this.deliveredIcon = "assets/message-delivered.svg";
this.sentIcon = "assets/message-sent.svg";
this.waitIcon = "assets/wait.svg";
this.errorIcon = "assets/warning-small.svg";
this.aiErrorIcon = "assets/ai-error.svg";
this.aiEmptyIcon = "assets/ai-empty.svg";
this.alignment = MessageListAlignment.standard;
this.showAvatar = true;
this.datePattern = DatePatterns.time;
this.timestampAlignment = TimestampAlignment.bottom;
this.DateSeparatorPattern = DatePatterns.DayDateTime;
this.templates = [];
this.newMessageIndicatorText = "";
this.scrollToBottomOnNewMessages = false;
this.thresholdValue = 1000;
this.unreadMessageThreshold = 30;
this.reactionsConfiguration = new ReactionsConfiguration({});
this.disableReactions = false;
this.emojiKeyboardStyle = {};
this.threadIndicatorIcon = "assets/threadIndicatorIcon.svg";
this.avatarStyle = {
borderRadius: "16px",
width: "28px",
height: "28px",
};
this.backdropStyle = {
height: "100%",
width: "100%",
background: "rgba(0, 0, 0, 0.5)",
position: "fixed",
};
this.dateSeparatorStyle = {
height: "",
width: "",
};
this.messageListStyle = {
nameTextFont: "400 11px Inter",
emptyStateTextFont: "700 22px Inter",
errorStateTextFont: "700 22px Inter",
};
this.onError = (error) => {
console.log(error);
};
this.messageInformationConfiguration = new MessageInformationConfiguration({});
this.disableMentions = false;
this.state = States.loading;
this.optionsStyle = {
width: "",
height: "",
border: "1px solid #e8e8e8",
borderRadius: "8px",
background: "white",
submenuWidth: "100%",
submenuHeight: "100%",
submenuBorder: "1px solid #e8e8e8",
submenuBorderRadius: "8px",
submenuBackground: "white",
moreIconTint: "grey",
};
this.receiptStyle = {};
this.documentBubbleAlignment = DocumentIconAlignment.right;
this.callBubbleAlignment = DocumentIconAlignment.left;
this.imageModerationStyle = {};
this.timestampEnum = TimestampAlignment;
this.chatChanged = true;
this.starterErrorStateText = localize("SOMETHING_WRONG");
this.starterEmptyStateText = localize("NO_MESSAGES_FOUND");
this.starterLoadingStateText = localize("GENERATING_ICEBREAKERS");
this.summaryErrorStateText = localize("SOMETHING_WRONG");
this.summaryEmptyStateText = localize("NO_MESSAGES_FOUND");
this.summaryLoadingStateText = localize("GENERATING_SUMMARY");
this.timeStampColor = "";
this.timeStampFont = "";
this.smartReplyStyle = {
width: "100%",
height: "100%",
border: "none",
};
this.conversationStarterStyle = {};
this.conversationSummaryStyle = {
width: "100%",
height: "100%",
border: "none",
titleFont: "",
titleColor: "",
closeIconTint: "",
boxShadow: "",
textFont: "",
textColor: "",
background: "",
};
this.showSmartReply = false;
this.enableConversationStarter = false;
this.showConversationStarter = false;
this.conversationStarterState = States.loading;
this.conversationStarterReplies = [];
this.enableConversationSummary = false;
this.showConversationSummary = false;
this.conversationSummaryState = States.loading;
this.conversationSummary = [];
this.getUnreadCount = 0;
this.smartReplyMessage = null;
this.enableSmartReply = false;
this.timeStampBackground = "";
this.linkPreviewStyle = {};
this.unreadMessagesStyle = {};
this.modalStyle = {
height: "fit-content",
width: "fit-content",
closeIconTint: "blue",
};
this.dividerStyle = {
height: "1px",
width: "100%",
background: "grey",
};
this.pollBubbleStyle = {};
this.labelStyle = {
textFont: "400 11px Inter",
textColor: "grey",
};
this.imageBubbleStyle = {
height: "auto",
width: "100%",
border: "none",
borderRadius: "8px 8px 0px 0px",
background: "transparent",
};
this.messagesList = [];
this.bubbleDateStyle = {};
this.whiteboardIconURL = "assets/collaborativewhiteboard.svg";
this.documentIconURL = "assets/collaborativedocument.svg";
this.directCallIconURL = "assets/Video-call2x.svg";
this.placeholderIconURL = "/assets/placeholder.png";
this.downloadIconURL = "assets/download.svg";
this.translationStyle = {};
this.documentBubbleStyle = {};
this.callBubbleStyle = {};
this.whiteboardTitle = localize("COLLABORATIVE_WHITEBOARD");
this.whiteboardSubitle = localize("DRAW_WHITEBOARD_TOGETHER");
this.whiteboardButtonText = localize("OPEN_WHITEBOARD");
this.documentTitle = localize("COLLABORATIVE_DOCUMENT");
this.documentSubitle = localize("DRAW_DOCUMENT_TOGETHER");
this.documentButtonText = localize("OPEN_DOCUMENT");
this.joinCallButtonText = localize("JOIN");
this.localize = localize;
this.reinitialized = false;
this.addReactionIconURL = "assets/addreaction.svg";
this.MessageTypesConstant = CometChatUIKitConstants.MessageTypes;
this.callConstant = CometChatUIKitConstants.MessageCategory.call;
this.typesMap = {};
this.messageTypesMap = {};
this.theme = new CometChatTheme({});
this.groupListenerId = "group_" + new Date().getTime();
this.callListenerId = "call_" + new Date().getTime();
this.states = States;
this.MessageCategory = CometChatUIKitConstants.MessageCategory;
this.numberOfTopScroll = 0;
this.keepRecentMessages = true;
this.messageTemplate = [];
this.openContactsView = false;
this.isOnBottom = false;
this.UnreadCount = [];
this.newMessageCount = 0;
this.type = "";
this.confirmText = localize("YES");
this.cancelText = localize("NO");
this.warningText = "Are you sure want to see unsafe content?";
this.threadedAlignment = MessageBubbleAlignment.left;
this.messageInfoAlignment = MessageBubbleAlignment.right;
this.openEmojiKeyboard = false;
this.keyboardAlignment = Placement.right;
this.popoverStyle = {
height: "330px",
width: "325px",
};
this.videoBubbleStyle = {
height: "130px",
width: "230px",
border: "none",
borderRadius: "8px",
background: "transparent",
};
this.threadViewAlignment = MessageBubbleAlignment.left;
this.enableDataMasking = false;
this.enableThumbnailGeneration = false;
this.enableLinkPreview = false;
this.enablePolls = false;
this.enableReactions = false;
this.enableImageModeration = false;
this.enableStickers = false;
this.enableWhiteboard = false;
this.enableDocument = false;
this.showOngoingCall = false;
this.enableCalling = false;
this.ongoingCallStyle = {};
this.sessionId = "";
this.openMessageInfoPage = false;
this.firstReload = false;
this.isWebsocketReconnected = false;
this.connectionListenerId = "connection_" + new Date().getTime();
this.lastMessageId = 0;
this.isConnectionReestablished = false;
this.closeIconURL = "assets/close2x.svg";
this.threadOpenIcon = "assets/side-arrow.svg";
this.confirmDialogStyle = {};
this.messageToReact = null;
this.limit = 30;
this.types = [];
this.categories = [];
this.callbacks = new Map();
this.closeContactsPage = () => {
this.openContactsView = false;
this.ref.detectChanges();
};
this.addReaction = (event) => {
let emoji = event?.detail?.id;
this.popoverRef.nativeElement.openContentView(event);
if (this.messageToReact) {
this.reactToMessage(emoji, this.messageToReact);
}
};
this.getCallActionMessage = (call) => {
return CallingDetailsUtils.getCallStatus(call, this.loggedInUser);
};
this.isMobileView = () => {
return window.innerWidth <= 768;
};
this.showEmojiKeyboard = (id, event) => {
let message = this.getMessageById(id);
if (message) {
this.messageToReact = message;
if (this.isMobileView()) {
let bubbleRef = this.getBubbleById(String(id));
if (bubbleRef) {
const rect = bubbleRef.nativeElement.getBoundingClientRect();
const isAtTop = rect.top < innerHeight / 2;
const isAtBottom = rect.bottom > window.innerHeight / 2;
if (isAtTop) {
this.keyboardAlignment = Placement.bottom;
}
else if (isAtBottom) {
this.keyboardAlignment = Placement.top;
}
}
}
else {
this.keyboardAlignment =
message.getSender()?.getUid() == this.loggedInUser?.getUid()
? Placement.left
: Placement.right;
}
this.ref.detectChanges();
this.popoverRef.nativeElement.openContentView(event);
}
};
this.setBubbleView = () => {
this.messageTemplate.forEach((element) => {
this.messageTypesMap[element.category + '_' + element.type] = element;
});
};
this.openThreadView = (message) => {
if (this.onThreadRepliesClick) {
this.onThreadRepliesClick(message, this.threadMessageBubble);
}
};
this.threadCallback = (id) => {
let messageObject = this.getMessageById(id);
this.openThreadView(messageObject);
};
this.deleteCallback = (id) => {
let messageObject = this.getMessageById(id);
this.deleteMessage(messageObject);
};
this.editCallback = (id) => {
let messageObject = this.getMessageById(id);
this.onEditMessage(messageObject);
};
this.copyCallback = (id) => {
let messageObject = this.getMessageById(id);
this.onCopyMessage(messageObject);
};
this.messagePrivatelyCallback = (id) => {
let messageObject = this.getMessageById(id);
this.sendMessagePrivately(messageObject);
};
this.messageInfoCallback = (id) => {
let messageObject = this.getMessageById(id);
this.openMessageInfo(messageObject);
};
this.closeMessageInfoPage = () => {
this.openMessageInfoPage = false;
this.ref.detectChanges();
};
this.updateTranslatedMessage = (translation) => {
var receivedMessage = translation;
var translatedText = receivedMessage.translations[0].message_translated;
let messageList = [...this.messagesList];
let messageKey = messageList.findIndex((m) => m.getId() === receivedMessage.msgId);
let data;
if (messageKey > -1) {
var messageObj = messageList[messageKey];
if (messageObj.getMetadata()) {
data = messageObj.getMetadata();
}
else {
messageObj.setMetadata({});
data = messageObj.getMetadata();
}
data[MessageTranslationConstants.translated_message] = translatedText;
var newMessageObj = messageObj;
messageList.splice(messageKey, 1, newMessageObj);
this.messagesList = [...messageList];
this.ref.detectChanges();
}
};
this.translateMessage = (id) => {
let message = this.getMessageById(id);
if (message) {
CometChat.callExtension(MessageTranslationConstants.message_translation, MessageTranslationConstants.post, MessageTranslationConstants.v2_translate, {
msgId: message.getId(),
text: message.getText(),
languages: navigator.languages,
})
.then((result) => {
if (result?.translations[0]?.message_translated !=
message?.getText()) {
this.updateTranslatedMessage(result);
this.ref.detectChanges();
}
else {
return;
}
// Result of translations
})
.catch((error) => { });
}
};
/**
* Filters out the 'add reaction' option if reactions are disabled.
*
* @param {CometChatMessageOption[]} options - The original set of message options.
* @returns {CometChatMessageOption[]} The filtered set of message options.
*/
this.filterEmojiOptions = (options) => {
if (!this.disableReactions) {
return options;
}
return options.filter((option) => {
return option.id !== CometChatUIKitConstants.MessageOption.reactToMessage;
});
};
/**
* Checks if the 'statusInfoView' is present in the default template provided by the user
* If present, returns the user-defined template, otherwise returns null.
*
* @param message Message object for which the status info view needs to be fetched
* @returns User-defined TemplateRef if present, otherwise null
*/
this.getContentView = (message) => {
if (this.messageTypesMap[message.getCategory() + '_' + message?.getType()] &&
this.messageTypesMap[message.getCategory() + '_' + message?.getType()]?.contentView) {
return this.messageTypesMap[message.getCategory() + '_' + message?.getType()]?.contentView(message);
}
else {
return message.getDeletedAt()
? this.typesMap[CometChatUIKitConstants.MessageCategory.message + '_' + CometChatUIKitConstants.MessageTypes.text]
: this.typesMap[message.getCategory() + '_' + message?.getType()];
}
};
this.setBubbleAlignment = (message) => {
let alignment = MessageBubbleAlignment.center;
if (this.alignment == MessageListAlignment.left) {
alignment = MessageBubbleAlignment.left;
}
else {
if (message?.getType() ==
CometChatUIKitConstants.MessageTypes.groupMember ||
message.getCategory() == this.callConstant) {
alignment = MessageBubbleAlignment.center;
}
else if (!message?.getSender() ||
(message?.getSender().getUid() == this.loggedInUser.getUid() &&
message?.getType() !=
CometChatUIKitConstants.MessageTypes.groupMember)) {
alignment = MessageBubbleAlignment.right;
}
else {
alignment = MessageBubbleAlignment.left;
}
}
return alignment;
};
this.getBubbleWrapper = (message) => {
let view;
if (this.messageTypesMap &&
this.messageTypesMap[message?.getCategory() + '_' + message?.getType()] &&
this.messageTypesMap[message?.getCategory() + '_' + message?.getType()].bubbleView) {
view = this.messageTypesMap[message?.getCategory() + '_' + message?.getType()].bubbleView(message);
return view;
}
else {
view = null;
return view;
}
};
this.setTranslationStyle = (message) => {
var isLeftAligned = this.alignment !== MessageListAlignment.left;
var isUserSentMessage = !message?.getSender() ||
this.loggedInUser.getUid() === message?.getSender().getUid();
if (!isLeftAligned) {
return new MessageTranslationStyle({
translatedTextFont: fontHelper(this.themeService.theme.typography.text3),
translatedTextColor: this.themeService.theme.palette.getAccent("light"),
helpTextColor: this.themeService.theme.palette.getAccent700(),
helpTextFont: fontHelper(this.themeService.theme.typography.caption2),
background: "transparent",
});
}
else {
if (isUserSentMessage) {
return new MessageTranslationStyle({
translatedTextFont: fontHelper(this.themeService.theme.typography.text3),
translatedTextColor: this.themeService.theme.palette.getAccent("dark"),
helpTextColor: this.themeService.theme.palette.getAccent700("dark"),
helpTextFont: fontHelper(this.themeService.theme.typography.caption2),
background: "transparent",
});
}
else {
return new MessageTranslationStyle({
translatedTextFont: fontHelper(this.themeService.theme.typography.text3),
translatedTextColor: this.themeService.theme.palette.getAccent("light"),
helpTextColor: this.themeService.theme.palette.getAccent700(),
helpTextFont: fontHelper(this.themeService.theme.typography.caption2),
background: "transparent",
});
}
}
};
this.setTextBubbleStyle = (message) => {
let isInfoBubble = this.messageInfoObject && message.getId() && this.messageInfoObject.getId() == message.getId();
var isDeleted = message.getDeletedAt();
var notLeftAligned = this.alignment !== MessageListAlignment.left;
var isTextMessage = message.getCategory() ===
CometChatUIKitConstants.MessageCategory.message &&
message?.getType() === CometChatUIKitConstants.MessageTypes.text;
var isUserSentMessage = !message?.getSender() ||
this.loggedInUser.getUid() === message?.getSender().getUid();
var isGroupMemberMessage = message?.getType() === CometChatUIKitConstants.MessageTypes.groupMember;
if (!isDeleted && notLeftAligned && isTextMessage && isUserSentMessage) {
return {
textFont: fontHelper(this.themeService.theme.typography.text3),
textColor: this.themeService.theme.palette.getAccent900("light"),
bubblePadding: isInfoBubble ? "8px 12px" : "8px 12px 0 12px"
};
}
if (!isDeleted &&
notLeftAligned &&
isTextMessage &&
!isUserSentMessage &&
!isGroupMemberMessage) {
return {
textFont: fontHelper(this.themeService.theme.typography.text3),
textColor: this.themeService.theme.palette.getAccent(),
bubblePadding: "8px 12px 2px 12px"
};
}
if (isGroupMemberMessage) {
return {
textFont: fontHelper(this.themeService.theme.typography.subtitle2),
textColor: this.themeService.theme.palette.getAccent600(),
};
}
if (!notLeftAligned && isTextMessage) {
return {
textFont: fontHelper(this.themeService.theme.typography.text2),
textColor: this.themeService.theme.palette.getAccent(),
};
}
return {
textFont: fontHelper(this.themeService.theme.typography.text2),
textColor: this.themeService.theme.palette.getAccent400(),
bubblePadding: "8px 12px"
};
};
/*
* isPartOfCurrentChatForUIEvent: To check if the message belongs for this list and is not part of thread even for current list
it only runs for UI event because it assumes logged in user is always sender
* @param: message: CometChat.BaseMessage
*/
this.isPartOfCurrentChatForUIEvent = (message) => {
const receiverId = message?.getReceiverId();
const receiverType = message?.getReceiverType();
if (this.parentMessageId) {
if (message.getParentMessageId() === this.parentMessageId) {
return true;
}
else {
return false;
}
}
else {
if (message.getParentMessageId()) {
return false;
}
if (this.user) {
if (receiverType === CometChatUIKitConstants.MessageReceiverType.user && receiverId === this.user.getUid()) {
return true;
}
}
else if (this.group) {
if (receiverType === CometChatUIKitConstants.MessageReceiverType.group && receiverId === this.group.getGuid()) {
return true;
}
}
return false;
}
};
/*
* isPartOfCurrentChatForSDKEvent: To check if the message belongs for this list and is not part of thread even for current list
it only runs for SDK event because it needs senderId to check if the message is sent by the same user
* @param: message: CometChat.BaseMessage
*/
this.isPartOfCurrentChatForSDKEvent = (message) => {
const receiverId = message?.getReceiverId();
const receiverType = message?.getReceiverType();
const senderId = message?.getSender()?.getUid();
if (this.parentMessageId) {
if (message.getParentMessageId() === this.parentMessageId) {
return true;
}
else {
return false;
}
}
else {
if (message.getParentMessageId()) {
return false;
}
if (this.user) {
if (receiverType === CometChatUIKitConstants.MessageReceiverType.user && (receiverId === this.user.getUid() || senderId === this.user.getUid())) {
return true;
}
else {
return false;
}
}
else if (this.group) {
if (receiverType === CometChatUIKitConstants.MessageReceiverType.group && (receiverId === this.group.getGuid())) {
return true;
}
else {
return false;
}
}
return false;
}
};
/*
* isThreadOfCurrentChatForUIEvent: To check if the message belongs thread of this list,
it only runs for UI event because it assumes logged in user is always sender
* @param: message: CometChat.BaseMessage
*/
this.isThreadOfCurrentChatForUIEvent = (message) => {
if (!message.getParentMessageId()) {
return false;
}
const receiverId = message?.getReceiverId();
if (this.user) {
if (receiverId === this.user.getUid()) {
return true;
}
}
else if (this.group) {
if (receiverId === this.group.getGuid()) {
return true;
}
}
return false;
};
/*
* isThreadOfCurrentChatForSDKEvent: To check if the message belongs thread of this list,
it only runs for SDK event because it needs senderId to check if the message is sent by the same user
* @param: message: CometChat.BaseMessage
*/
this.isThreadOfCurrentChatForSDKEvent = (message) => {
if (!message.getParentMessageId()) {
return false;
}
const receiverId = message?.getReceiverId();
const senderId = message?.getSender()?.getUid();
if (this.user) {
if (receiverId === this.user.getUid() || senderId === this.user.getUid()) {
return true;
}
}
else if (this.group) {
if (receiverId === this.group.getGuid()) {
return true;
}
}
return false;
};
this.startDirectCall = (sessionId, message) => {
this.sessionId = sessionId;
this.showOngoingCall = true;
StorageUtils.setItem(CometChatUIKitConstants.calls.activecall, message);
this.ref.detectChanges();
};
this.launchCollaborativeWhiteboardDocument = (url) => {
window.open(url + `&username=${this.loggedInUser?.getName()}`, "", "fullscreen=yes, scrollbars=auto");
};
this.openConfirmDialog = false;
this.openFullscreenView = false;
this.imageurlToOpen = "";
this.fullScreenViewerStyle = {
closeIconTint: "blue",
};
this.onConfirmClick = () => {
this.openConfirmDialog = false;
if (this.closeImageModeration) {
this.closeImageModeration();
}
this.ref.detectChanges();
};
this.setOngoingCallStyle = () => {
let defaultStyle = new CallscreenStyle({
maxHeight: "100%",
maxWidth: "100%",
border: "none",
borderRadius: "0",
background: "#1c2226",
minHeight: "400px",
minWidth: "400px",
minimizeIconTint: this.themeService.theme.palette.getAccent900(),
maximizeIconTint: this.themeService.theme.palette.getAccent900(),
});
this.ongoingCallStyle = { ...defaultStyle, ...this.ongoingCallStyle };
};
/**
* Listener To Receive Messages in Real Time
* @param
*/
this.fetchPreviousMessages = () => {
if (this.reinitialized) {
if (this.messagesRequestBuilder) {
this.requestBuilder = CometChatUIKitUtility.clone(this.messagesRequestBuilder);
}
else {
this.requestBuilder = new CometChat.MessagesRequestBuilder()
.setLimit(this.limit)
.setTypes(this.types)
.setMessageId(this.messagesList[0].getId())
.setCategories(this.categories)
.hideReplies(true);
if (this.user) {
this.requestBuilder = this.requestBuilder.setUID(this.user?.getUid()).build();
}
else if (this.group) {
this.requestBuilder = this.requestBuilder.setGUID(this.group?.getGuid()).build();
}
}
}
this.requestBuilder
.fetchPrevious()
.then((messageList) => {
if (messageList && messageList.length > 0) {
messageList = messageList.map((message, i) => {
if (message.getCategory() ===
CometChatUIKitConstants.MessageCategory.interactive) {
return InteractiveMessageUtils.convertInteractiveMessage(message);
}
else {
return message;
}
});
}
this.state = States.loading;
// No Messages Found
if (messageList.length === 0 && this.messagesList.length === 0) {
this.state = States.empty;
if (!this.parentMessageId && this.enableConversationStarter) {
this.fetchConversationStarter();
}
this.ref.detectChanges();
return;
}
if (messageList && messageList.length > 0) {
if (this.getUnreadCount >= this.unreadMessageThreshold &&
this.enableConversationSummary) {
this.fetchConversationSummary();
}
this.showConversationStarter = false;
this.conversationStarterReplies = [];
if (this.firstReload) {
this.lastMessageId = Number(messageList[messageList.length - 1].getId());
}
let lastMessage = messageList[messageList.length - 1];
let isSentByMe = lastMessage?.getSender()?.getUid() ==
this.loggedInUser?.getUid();
if (!isSentByMe &&
!lastMessage.getDeliveredAt()) {
//mark the message as delivered
if (!this.disableReceipt) {
CometChat.markAsDelivered(lastMessage).then((receipt) => {
let messageKey = this.messagesList.findIndex((m) => m.getId() === Number(receipt?.getMessageId()));
if (messageKey > -1) {
this.markAllMessagAsDelivered(messageKey);
}
});
}
}
if (!lastMessage?.getReadAt() && !isSentByMe) {
if (!this.disableReceipt) {
CometChat.markAsRead(lastMessage)
.then((receipt) => {
let messageKey = this.messagesList.findIndex((m) => m.getId() === Number(receipt?.getMessageId()));
if (messageKey > -1) {
this.markAllMessagAsRead(messageKey);
}
})
.catch((error) => {
if (this.onError) {
this.onError(error);
}
});
}
else {
this.UnreadCount = [];
this.ref.detectChanges();
}
}
this.state = States.loaded;
this.ref.detectChanges();
//if the sender of the message is not the loggedin user, mark it as read.
let prevScrollHeight = this.listScroll?.nativeElement.scrollHeight;
setTimeout(() => {
this.listScroll.nativeElement.scrollTop =
this.listScroll?.nativeElement.scrollHeight - prevScrollHeight;
}, 100);
this.showSmartReply = false;
this.smartReplyMessage = null;
this.prependMessages(messageList);
}
else {
this.state = States.loaded;
}
if (this.firstReload) {
this.attachConnectionListener();
this.firstReload = false;
}
this.ref.detectChanges();
}, (error) => {
this.state = States.error;
if (this.onError) {
this.onError(CometChatException(error));
}
this.ref.detectChanges();
})
.catch((error) => {
if (this.onError) {
this.onError(error);
}
if (this.messagesList?.length <= 0) {
this.state = States.error;
this.ref.detectChanges();
}
});
};
this.fetchNextMessage = () => {
let index = this.messagesList.length - 1;
let messageId;
if (this.reinitialized ||
(this.lastMessageId > 0 && this.isWebsocketReconnected)) {
if (this.isWebsocketReconnected) {
this.fetchActionMessages();
messageId = this.lastMessageId;
}
else {
messageId = this.messagesList[index].getId();
}
if (this.messagesRequestBuilder) {
this.requestBuilder = this.user
? this.messagesRequestBuilder
.setUID(this.user?.getUid())
.setMessageId(messageId)
.build()
: this.messagesRequestBuilder
.setGUID(this.group?.getGuid())
.setMessageId(messageId)
.build();
}
else {
this.requestBuilder = new CometChat.MessagesRequestBuilder()
.setLimit(this.limit)
.setTypes(this.types)
.setMessageId(messageId)
.setCategories(this.categories)
.hideReplies(true);
if (this.user) {
this.requestBuilder.setUID(this.user?.getUid()).build();
}
else if (this.group) {
this.requestBuilder.setGUID(this.group?.getGuid()).build();
}
}
this.requestBuilder
.fetchNext()
.then((messageList) => {
if (messageList && messageList.length > 0) {
messageList = messageList.map((message, i) => {
if (message.getCategory() ===
CometChatUIKitConstants.MessageCategory.interactive) {
return InteractiveMessageUtils.convertInteractiveMessage(message);
}
else {
return message;
}
});
}
this.state = States.loading;
// No Messages Found
if (messageList.length === 0 && this.messagesList.length === 0) {
this.state = States.empty;
this.ref.detectChanges();
return;
}
if (messageList && messageList.length) {
if (this.isOnBottom) {
let lastMessage = messageList[messageList.length - 1];
this.lastMessageId = Number(messageList[messageList.length - 1].getId());
this.firstReload = false;
if (!lastMessage?.getReadAt() &&
lastMessage?.getSender().getUid() !=
this.loggedInUser?.getUid()) {
if (!this.disableReceipt) {
CometChat.markAsRead(lastMessage);
}
else {
this.UnreadCount = [];
this.ref.detectChanges();
}
}
if (!lastMessage?.getDeliveredAt() &&
lastMessage?.getSender().getUid() !=
this.loggedInUser?.getUid()) {
this.markMessageAsDelivered(lastMessage);
this.markAllMessagAsDelivered(messageList.length - 1);
}
this.state = States.loaded;
this.scrollToBottom();
this.appendMessages(messageList);
this.isWebsocketReconnected = false;
this.ref.detectChanges();
}
else {
let lastMessage = messageList[messageList.length - 1];
this.lastMessageId = Number(messageList[messageList.length - 1].getId());
this.firstReload = false;
if (this.scrollToBottomOnNewMessages) {
setTimeout(() => {
this.scrollToBottom();
}, 100);
}
else {
let countText = localize("NEW_MESSAGES");
if (this.newMessageIndicatorText &&
this.newMessageIndicatorText != "") {
countText = this.newMessageIndicatorText;
}
else {
countText =
this.UnreadCount.length > 0
? localize("NEW_MESSAGES")
: localize("NEW_MESSAGE");
}
this.UnreadCount.push(...messageList);
this.newMessageCount =
" ↓ " + this.UnreadCount.length + " " + countText;
this.ref.detectChanges();
}
if (!lastMessage?.getDeliveredAt() &&
lastMessage?.getSender().getUid() !=
this.loggedInUser?.getUid()) {
this.markMessageAsDelivered(lastMessage);
this.markAllMessagAsDelivered(messageList.length - 1);
}
this.state = States.loaded;
this.appendMessages(messageList);
this.isWebsocketReconnected = false;
this.ref.detectChanges();
}
}
}, (error) => {
this.state = States.error;
console.log(error);
if (this.onError) {
this.onError(CometChatException(error));
}
this.ref.detectChanges();
})
.catch((error) => {
if (this.onError) {
this.onError(error);
}
if (this.messagesList?.length <= 0) {
this.state = States.error;
this.ref.detectChanges();
}
});
}
};
this.appendMessages = (messages) => {
if (!this.isPartOfCurrentChatForSDKEvent(messages[0])) {
return;
}
this.messagesList.push(...messages);
this.messageCount = this.messagesList.length;
if (this.messageCount > this.thresholdValue) {
this.keepRecentMessages = true;
this.reInitializeMessageBuilder();
}
this.state = States.loaded;
this.ref.detectChanges();
};
/**
* translate message then call update message
* @param {CometChat.BaseMessage} message
*/
// translateMessage(message: CometChat.BaseMessage) {
// }
/**
* @param {CometChat.BaseMessage} message
*/
this.markMessageAsDelivered = (message) => {
if (!this.disableReceipt &&
message?.getSender().getUid() !== this.loggedInUser?.getUid() &&
message.hasOwnProperty("deliveredAt") === false) {
CometChat.markAsDelivered(message);
}
};
/**
* @param {CometChat.BaseMessage} message
* @param {string} type
*/
this.messageReceivedHandler = (message) => {
++this.messageCount;
if (message.getParentMessageId()) {
// this.updateReplyCount(message);
this.updateUnreadReplyCount(message);
this.addMessage(message);
}
else {
if (this.messageCount > this.thresholdValue) {
this.keepRecentMessages = true;
this.reInitializeMessageBuilder();
}
this.addMessage(message);
if (!this.isOnBottom) {
if (this.scrollToBottomOnNewMessages) {
setTimeout(() => {
this.scrollToBottom();
}, 100);
}
else {
let countText = localize("NEW_MESSAGES");
if (this.newMessageIndicatorText &&
this.newMessageIndicatorText != "") {
countText = this.newMessageIndicatorText;
}
else {
countText =
this.UnreadCount.length > 0
? localize("NEW_MESSAGES")
: localize("NEW_MESSAGE");
}
this.UnreadCount.push(message);
this.newMessageCount =
" ↓ " + this.UnreadCount.length + " " + countText;
this.ref.detectChanges();
}
}
}
if (!this.disableSoundForMessages) {
this.playAudio();
}
//handling dom lag - increment count only for main message list
if (message.hasOwnProperty("parentMessageId") === false &&
this.parentMessageId) {
++this.messageCount;
this.ref.detectChanges();
}
else if (message.hasOwnProperty("parentMessageId") === true &&
this.parentMessageId) {
if (message.getParentMessageId() === this.parentMessageId &&
this.isOnBottom) {
if (!this.disableReceipt) {
CometChat.markAsRead(message).then(() => {
CometChatMessageEvents.ccMessageRead.next(message);
});
}
else {
this.UnreadCount = [];
this.ref.detectChanges();
}
this.ref.detectChanges();
}
}
else {
}
};
this.getCallBuilder = () => {
const callSettings = new CometChatUIKitCalls.CallSettingsBuilder()
.enableDefaultLayout(true)
.setIsAudioOnlyCall(false)
.setCallListener(new CometChatUIKitCalls.OngoingCallListener({
onCallEndButtonPressed: () => {
StorageUtils.setItem(CometChatUIKitConstants.calls.activecall, null);
CometChatCallEvents.ccCallEnded.next({});
},
onError: (error) => {
if (this.onError) {
this.onError(error);
}
},
}))
.build();
return callSettings;
};
this.reInitializeMessageBuilder = () => {
if (!this.parentMessageId) {
this.messageCount = 0;
}
this.requestBuilder = null;
CometChat.removeGroupListener(this.groupListenerId);
CometChat.removeCallListener(this.callListenerId);
this.reInitializeMessageList();
};
/**
* Emits an Action Indicating that a message was deleted by the user/person you are chatting with
* @param {CometChat.BaseMessage} message
*/
/**
* Detects if the message that was edit is your current open conversation window
* @param {CometChat.BaseMessage} message
*/
this.messageEdited = (message) => {
try {
if (this.group &&
message.getReceiverType() ===