isomtrik-quickchat
Version:
isomtrik-quickchat is a lightweight, real-time chat component built with Stencil JS. It is designed to be seamlessly integrated into web applications, offering customizable and responsive chat functionalities. The module supports both CommonJS and ES modu
425 lines (421 loc) • 21.6 kB
JavaScript
import { r as registerInstance, h } from './index-6a4e4ae9.js';
import { g as getDeviceID, w } from './index.m-ef6bdd51.js';
/**
* @fileoverview entry point for your component library
*
* This is the entry point for your component library. Use this file to export utilities,
* constants or data structure that accompany your components.
*
* DO NOT use this file to export your components. Instead, use the recommended approaches
* to consume components of this package as outlined in the `README.md`.
*/
const initializeChat = function (props) {
if (!props.conversationId ||
!props.licenseKey ||
!props.appSecret ||
!props.userSecret ||
!props.userToken ||
!props.isometrikUserId ||
!props.projectId ||
!props.keysetId ||
!props.accountId) {
console.error('Missing required props to Initialize chat!');
return;
}
const existingChatComponent = document.getElementById(`${props.conversationId}`);
if (existingChatComponent) {
console.warn(`Chat component for ${props.conversationId} already exists.`);
return;
}
const chatComponent = document.createElement('chat-test');
chatComponent.id = props.conversationId;
chatComponent.baseUrl = (props === null || props === void 0 ? void 0 : props.baseUrl) || 'https://apis.isometrik.io';
chatComponent.hostUrl = (props === null || props === void 0 ? void 0 : props.hostUrl) || 'wss://connections.isometrik.io:2053/mqtt';
chatComponent.licenseKey = props.licenseKey;
chatComponent.appSecret = props.appSecret;
chatComponent.userSecret = props.userSecret;
chatComponent.userToken = props.userToken;
chatComponent.isometrikUserId = props.isometrikUserId;
chatComponent.projectId = props.projectId;
chatComponent.keysetId = props.keysetId;
chatComponent.accountId = props.accountId;
chatComponent.conversationId = props.conversationId;
chatComponent.isDark = props.defaultTheme == 'dark' ? true : false;
chatComponent.darkThemeUrl = props.darkThemeUrl || 'https://isometrik-website-bucket.s3.ap-south-1.amazonaws.com/styles/chat-dark-theme.css';
chatComponent.lightThemeUrl = props.lightThemeUrl || 'https://isometrik-website-bucket.s3.ap-south-1.amazonaws.com/styles/chat-light-theme.css';
document.body.appendChild(chatComponent);
};
const closeChat = function (conversationId) {
if (!conversationId) {
console.error('conversationId is require to closeChat');
return;
}
const chatComponent = document.getElementById(conversationId);
if (chatComponent) {
chatComponent.baseUrl = null;
chatComponent.hostUrl = null;
chatComponent.licenseKey = null;
chatComponent.appSecret = null;
chatComponent.userSecret = null;
chatComponent.userToken = null;
chatComponent.isometrikUserId = null;
chatComponent.projectId = null;
chatComponent.keysetId = null;
chatComponent.accountId = null;
chatComponent.conversationId = null;
document.body.removeChild(chatComponent);
}
};
const switchChatTheme = function (theme) {
const chatElements = document.getElementsByTagName('CHAT-TEST');
for (let i = 0; i < chatElements.length; i++) {
const chatTest = chatElements[i];
chatTest.isDark = theme == 'dark' ? true : false;
}
};
if (typeof window !== 'undefined') {
window.initializeChat = initializeChat;
window.closeChat = closeChat;
window.switchChatTheme = switchChatTheme;
}
const ChatTest = class {
constructor(hostRef) {
registerInstance(this, hostRef);
this.typingTimeout = null;
this.refetchInterval = null;
// State Update Methods
this.changeScrollToBottomState = (newState) => {
this.isScrollToBottom = newState;
};
this.changeScrollToTopState = (newState) => {
this.isScrollToTop = newState;
};
this.updateSkip = () => {
if (!this.isMessageLimitEnd) {
this.skip += 20;
}
};
this.updateAllMessages = (newMessages) => {
this.allMessages = newMessages;
};
this.refetchMessages = async () => {
this.isScrollToBottom = true;
this.skip = 0;
this.isMessageLimitEnd = false;
await this.getMessages(0);
};
this.changeMessageSendingState = (newState) => {
this.isMessageSending = newState;
};
this.baseUrl = undefined;
this.hostUrl = undefined;
this.licenseKey = undefined;
this.appSecret = undefined;
this.userSecret = undefined;
this.userToken = undefined;
this.isometrikUserId = undefined;
this.projectId = undefined;
this.keysetId = undefined;
this.accountId = undefined;
this.conversationId = undefined;
this.isDark = undefined;
this.darkThemeUrl = undefined;
this.lightThemeUrl = undefined;
this.isInitialized = false;
this.findUserId = {};
this.mqttClient = null;
this.mqttInitialized = false;
this.allMessages = [];
this.userMetaData = null;
this.conversationMetaData = null;
this.isMessageLimitEnd = false;
this.skip = 0;
this.isMessagesLoading = false;
this.isMessageSending = false;
this.deviceId = '';
this.isScrollToBottom = true;
this.isScrollToTop = false;
this.isChatClosed = false;
this.isChatMinimized = false;
this.isSubscribedToTopic = false;
this.isMessageListenerAttached = false;
this.isInitialCallDone = false;
this.isTyping = false;
}
async componentWillLoad() {
this.loadTheme();
try {
const deviceId = await getDeviceID();
this.deviceId = deviceId;
w.initializeInstance({
baseUrl: this.baseUrl,
licenseKey: this.licenseKey,
appSecret: this.appSecret,
userSecret: this.userSecret,
userToken: this.userToken,
});
this.isInitialized = true;
await this.setupMqttClient();
await this.getUserDetails();
await this.getUserConversationDetails();
if (!this.isMessageLimitEnd) {
await this.getMessages(this.skip);
}
}
catch (error) {
this.isInitialized = false;
console.error('ChatSDK initialization failed:', error);
}
}
cleanupMQTT() {
if (this.mqttClient && this.mqttClient.client) {
this.mqttClient.client.removeAllListeners('message');
if (this.refetchInterval) {
clearInterval(this.refetchInterval);
this.refetchInterval = null;
}
this.mqttClient = null;
this.mqttInitialized = false;
this.isSubscribedToTopic = false;
this.isMessageListenerAttached = false;
this.isInitialCallDone = false;
this.baseUrl = null;
this.hostUrl = null;
this.licenseKey = null;
this.appSecret = null;
this.userSecret = null;
this.userToken = null;
this.isometrikUserId = null;
this.projectId = null;
this.keysetId = null;
this.accountId = null;
this.conversationId = null;
}
}
async setupMqttClient() {
if (this.mqttClient) {
this.cleanupMQTT();
}
const mqttClient = w.getInstance().initializeMqtt({
hostUri: this.hostUrl,
clientId: this.isometrikUserId,
licenseKey: this.licenseKey,
projectId: this.projectId,
keysetId: this.keysetId,
accountId: this.accountId,
deviceId: this.deviceId,
});
this.mqttClient = mqttClient;
console.log(this.mqttClient, 'mqtt client');
if (this.mqttClient) {
this.mqttInitialized = true;
this.mqttClient.client.on('connect', async () => {
if (this.refetchInterval) {
clearInterval(this.refetchInterval);
this.refetchInterval = null;
}
if (!this.isInitialCallDone) {
await w.getInstance().message.putRead({ conversationId: this.conversationId });
await this.refetchMessages();
this.isInitialCallDone = true;
}
});
this.mqttClient.client.on('message', async (topic, message) => {
var _a, _b, _c, _d, _e, _f, _g;
const parsedMessage = JSON.parse(message.toString());
console.log(`klmnop new Incoming message form11111 ${topic}:1`, parsedMessage);
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) === 'messageRead') {
this.allMessages = (_a = this.allMessages) === null || _a === void 0 ? void 0 : _a.map(message => (message === null || message === void 0 ? void 0 : message.messageId) === (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.messageId) ? Object.assign(Object.assign({}, message), { readByAll: true }) : message);
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) === 'typingEvent' && parsedMessage.userId != this.userMetaData.userId) {
this.isTyping = true;
}
else {
this.isTyping = false;
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) === 'multipleMessagesRead' && parsedMessage.userId != ((_b = this.userMetaData) === null || _b === void 0 ? void 0 : _b.userId)) {
this.allMessages = (_c = this.allMessages) === null || _c === void 0 ? void 0 : _c.map(message => {
var _a, _b;
return (message === null || message === void 0 ? void 0 : message.readByAll) != true && ((message === null || message === void 0 ? void 0 : message.senderId) || ((_a = message === null || message === void 0 ? void 0 : message.senderInfo) === null || _a === void 0 ? void 0 : _a.userId)) == ((_b = this.userMetaData) === null || _b === void 0 ? void 0 : _b.userId)
? Object.assign(Object.assign({}, message), { readByAll: true }) : message;
});
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) == 'messagesDeleteForAll') {
this.allMessages = this.allMessages.filter((message) => message.messageId != parsedMessage.messageIds[0]);
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.senderId) == ((_d = this.userMetaData) === null || _d === void 0 ? void 0 : _d.userId) && (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) == 'chatMessageSent') {
this.changeMessageSendingState(false);
this.allMessages = this.allMessages.map(message => message.messageId == parsedMessage.messageId || message.id == '12'
? parsedMessage
: message);
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) == 'messageDelivered' && parsedMessage.senderId != ((_e = this.userMetaData) === null || _e === void 0 ? void 0 : _e.userId)) {
this.allMessages = (_f = this.allMessages) === null || _f === void 0 ? void 0 : _f.map(message => (message === null || message === void 0 ? void 0 : message.messageId) === (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.messageId)
? Object.assign(Object.assign({}, message), { deliveredToAll: true }) : message);
}
if ((parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.senderId) != ((_g = this.userMetaData) === null || _g === void 0 ? void 0 : _g.userId) &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) == 'chatMessageSent' &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) != 'typingEvent' &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) != 'messageRead' &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) != 'multipleMessagesRead' &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) != 'messageRead' &&
(parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.action) != 'messageDelivered') {
this.allMessages = [...this.allMessages, parsedMessage];
try {
await w.getInstance().message.putIndicateDelivered({
conversationId: parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.conversationId,
messageId: parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.messageId
});
}
catch (error) {
console.log(error, 'putIndicateDelivered request error');
}
}
});
this.mqttClient.client.on('error', (error) => {
console.log('MQTT connection error:--->', error);
this.isInitialCallDone = true;
if (!this.refetchInterval) {
this.refetchInterval = setInterval(() => {
console.log('MQTT connection failed, refetching messages...');
this.refetchMessages();
}, 30000);
}
});
}
}
async getUserDetails() {
var _a, _b, _c;
try {
const res = await w.getInstance().user.getUserDetails();
this.userMetaData = {
//@ts-ignore
userId: (res === null || res === void 0 ? void 0 : res.userId) || '',
userIdentifier: (res === null || res === void 0 ? void 0 : res.userIdentifier) || '',
//@ts-ignore
firstName: ((_a = res === null || res === void 0 ? void 0 : res.metaData) === null || _a === void 0 ? void 0 : _a.firstName) || '',
//@ts-ignore
lastName: ((_b = res === null || res === void 0 ? void 0 : res.metaData) === null || _b === void 0 ? void 0 : _b.lastName) || '',
updatedAt: (res === null || res === void 0 ? void 0 : res.updatedAt) || '',
userName: (res === null || res === void 0 ? void 0 : res.userName) || '',
online: (res === null || res === void 0 ? void 0 : res.online) || '',
userProfileImageUrl: (res === null || res === void 0 ? void 0 : res.userProfileImageUrl) || '',
//@ts-ignore
profilePic: ((_c = res === null || res === void 0 ? void 0 : res.metaData) === null || _c === void 0 ? void 0 : _c.profilePic) || '',
};
}
catch (error) {
console.error('getUserDetails fetching error:', error);
}
}
async getUserConversationDetails() {
try {
const res = await w.getInstance().Conversation.getConversationDetails({ conversationId: this.conversationId }, this.conversationId);
this.conversationMetaData = res.conversationDetails;
}
catch (error) {
console.error('getConversationDetails fetching error:', error);
}
}
async getMessages(skip) {
this.isMessagesLoading = true;
this.isScrollToTop = true;
try {
const res = await w.getInstance().message.getMessages({
conversationId: this.conversationId,
limit: 20,
skip: skip
});
if (skip === 0) {
this.allMessages = [...res.messages.reverse()];
}
else {
this.allMessages = [...res.messages.reverse(), ...this.allMessages];
}
}
catch (error) {
if (error.errorCode === 1) {
this.isMessageLimitEnd = true;
}
console.error('Error fetching messages:', error);
}
finally {
this.isMessagesLoading = false;
}
}
async deleteMessageFromSelf(payload) {
try {
this.allMessages = this.allMessages.filter((message) => message.messageId !== payload.messageIds);
await w.getInstance().message.deleteMessageSelf(payload);
}
catch (error) {
console.error('Delete self error:', error);
}
}
async deleteMeassageFromEveryOne(payload) {
try {
this.allMessages = this.allMessages.filter((message) => message.messageId !== payload.messageIds);
await w.getInstance().message.deleteMessagesEveryone(payload);
}
catch (error) {
console.error('Delete all error:', error);
}
}
// Watchers
handleSkipChange() {
if (!this.isMessageLimitEnd) {
this.getMessages(this.skip);
}
}
loadTheme() {
const themeLink = document.getElementById('theme-style');
if (themeLink) {
themeLink.href = this.isDark ? `${this.darkThemeUrl}` : `${this.lightThemeUrl}`;
}
else {
// Create a new link element if it doesn't exist
const link = document.createElement('link');
link.id = 'theme-style';
link.rel = 'stylesheet';
link.href = this.isDark ? `${this.darkThemeUrl}` : `${this.lightThemeUrl}`;
document.head.appendChild(link);
}
}
handleTypingChange() {
if (this.isTyping) {
if (this.typingTimeout) {
clearTimeout(this.typingTimeout);
}
this.typingTimeout = setTimeout(() => {
this.isTyping = false;
}, 10000);
}
}
disconnectedCallback() {
this.cleanupMQTT();
if (this.typingTimeout) {
clearTimeout(this.typingTimeout);
this.typingTimeout = null;
}
}
render() {
return (h("div", { key: '88bd56afdec0d1320cd2051514f16a685ca6b974' }, h("div", { key: '282e054e46e6dfc95de4946dcd0cf7898a65cddf', class: "isometrik-quickchat" }, !this.isChatClosed ? (this.isChatMinimized ? (h("div", { class: "minimizedChat" }, h("chat-header-closed", { conversationDetails: this.conversationMetaData, onMinimize: () => {
this.isChatMinimized = false;
}, onClose: () => {
closeChat(this.conversationId);
} }))) : (h("div", { class: "openChat" }, h("chat-header", { isDark: this.isDark, conversationDetails: this.conversationMetaData, onMinimize: () => {
this.isChatMinimized = true;
}, onClose: () => {
this.isChatClosed = true;
closeChat(this.conversationId);
}, isTyping: this.isTyping }), h("chat-body", { isDark: this.isDark, isMessagesLoading: this.isMessagesLoading, updateSkip: this.updateSkip, isMessageLimitEnd: this.isMessageLimitEnd, allMessages: this.allMessages, userMetaData: this.userMetaData, skip: this.skip, isScrollToBottom: this.isScrollToBottom, changeScrollToBottomState: this.changeScrollToBottomState, isMessageSending: this.isMessageSending, isScrollToTop: this.isScrollToTop, changeScrollToTopState: this.changeScrollToTopState, deleteForSelf: this.deleteMessageFromSelf, deleteForAll: this.deleteMeassageFromEveryOne, isChatClosed: this.isChatClosed, isChatMinimized: this.isChatMinimized, updateAllMessages: this.updateAllMessages, conversationId: this.conversationId }), h("chat-footer", { isDark: this.isDark, userMetaData: this.userMetaData, updateAllMessages: this.updateAllMessages, changeMessageSendingState: this.changeMessageSendingState, changeScrollToBottomState: this.changeScrollToBottomState, refetchMessages: this.refetchMessages, allMessages: this.allMessages, conversationId: this.conversationId })))) : null)));
}
static get watchers() { return {
"skip": ["handleSkipChange"],
"isDark": ["loadTheme"],
"isTyping": ["handleTypingChange"]
}; }
};
ChatTest.style = ":host {\n display: block;\n width: 95vw;\n max-width: 500px;\n position: fixed;\n right: 5px;\n bottom: 2px;\n box-shadow: 0px 0px 4px #6d5555;\n border-radius: 15px 15px 0px 0px;\n z-index: 2147483647 !important;\n background-color: #FFF;\n overflow: hidden;\n }\n\n .isometrik-quickchat {\n box-shadow: 0px 0px 20px 1px #6294a926;\n }\n .openChat {\n height: 90vh;\n display: flex;\n flex-direction: column;\n overflow: hidden; \n }";
export { ChatTest as chat_test };
//# sourceMappingURL=chat-test.entry.js.map