UNPKG

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

623 lines (622 loc) 27 kB
import { h } from "@stencil/core"; import ChatSDK from "test-iso-chat-sdk"; import { getDeviceID } from "../../../lib/helpers"; // import '../../../stories/Components/Head/Head'; // import '../../../stories/Components/Head/ClosedHeader/ClosedHead'; import "../../../global/app.css"; import { closeChat } from "../../../index"; import "./chat-test.css"; export class ChatTest { constructor() { 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; ChatSDK.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 = ChatSDK.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 ChatSDK.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 ChatSDK.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 ChatSDK.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 ChatSDK.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 ChatSDK.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 ChatSDK.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 ChatSDK.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 is() { return "chat-test"; } static get encapsulation() { return "shadow"; } static get styles() { return ":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 }"; } static get properties() { return { "baseUrl": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "base-url", "reflect": false }, "hostUrl": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "host-url", "reflect": false }, "licenseKey": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "license-key", "reflect": false }, "appSecret": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "app-secret", "reflect": false }, "userSecret": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "user-secret", "reflect": false }, "userToken": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "user-token", "reflect": false }, "isometrikUserId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "isometrik-user-id", "reflect": false }, "projectId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "project-id", "reflect": false }, "keysetId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "keyset-id", "reflect": false }, "accountId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "account-id", "reflect": false }, "conversationId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "conversation-id", "reflect": false }, "isDark": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "" }, "attribute": "is-dark", "reflect": false }, "darkThemeUrl": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "dark-theme-url", "reflect": false }, "lightThemeUrl": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "light-theme-url", "reflect": false } }; } static get states() { return { "isInitialized": {}, "findUserId": {}, "mqttClient": {}, "mqttInitialized": {}, "allMessages": {}, "userMetaData": {}, "conversationMetaData": {}, "isMessageLimitEnd": {}, "skip": {}, "isMessagesLoading": {}, "isMessageSending": {}, "deviceId": {}, "isScrollToBottom": {}, "isScrollToTop": {}, "isChatClosed": {}, "isChatMinimized": {}, "isSubscribedToTopic": {}, "isMessageListenerAttached": {}, "isInitialCallDone": {}, "isTyping": {} }; } static get watchers() { return [{ "propName": "skip", "methodName": "handleSkipChange" }, { "propName": "isDark", "methodName": "loadTheme" }, { "propName": "isTyping", "methodName": "handleTypingChange" }]; } } //# sourceMappingURL=chat-test.js.map