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
378 lines (377 loc) • 17 kB
JavaScript
import { h } from "@stencil/core";
import "../../../stories/Components/TestFooter/TestFooter";
// import { postMessage } from '../../../utils/chatSdk';
import "../../../stories/Components/AttachmentBox/AttachmentPreview/AttachmentPreview";
import ChatSDK from "test-iso-chat-sdk";
import { getDeviceID } from "../../../lib/helpers";
class ChatFooter {
constructor() {
this.handleInputChange = (event) => {
this.messageBody = event.detail.value;
this.debounceApiCall();
};
this.debounceApiCall = () => {
clearTimeout(this.debounceTimeout);
this.debounceTimeout = setTimeout(() => {
this.postTyping();
}, 300);
};
this.postTyping = async () => {
await ChatSDK.getInstance().message.postIndicateTyping({ conversationId: this.conversationId });
};
/////
this.handleFileUpload = (event) => {
const { file } = event.detail;
this.attachmentDetails = file;
if (file) {
const reader = new FileReader(); // Create a FileReader to read the file
reader.onload = (e) => {
var _a, _b, _c;
const fileType = file.type.split('/')[0];
if (fileType === 'image') {
this.imagePreviewSrc = (_a = e.target) === null || _a === void 0 ? void 0 : _a.result;
}
else if (fileType === 'video') {
this.videoPreviewSrc = (_b = e.target) === null || _b === void 0 ? void 0 : _b.result;
}
else if (fileType.startsWith('application')) {
this.pdfPreviewSrc = (_c = e.target) === null || _c === void 0 ? void 0 : _c.result;
}
};
reader.readAsDataURL(file); // Read the file as a Data URL (base64)
}
};
this.handleSendMessage = async () => {
var _a, _b, _c, _d, _e, _f;
if (!this.messageBody.trim() && !this.attachmentDetails) {
const singleLineText = this.messageBody.replace(/\n/g, ' ');
this.messageBody = singleLineText;
return;
}
this.changeScrollToBottomState(true);
const conversationId = this.conversationId;
const body = this.messageBody.trim();
this.messageBody = '';
if (body) {
this.updateAllMessages([
...this.allMessages,
{ body: body, messageId: '12', deliveredToAll: 'pending', senderId: this.userMetaData.userId, sentAt: Date.now() },
]);
this.changeMessageSendingState(true);
try {
const res = await ChatSDK.getInstance().message.postMessages({
showInConversation: true,
messageType: 0,
searchableTags: [body.slice(2).trim(), body.slice(3).trim()],
encrypted: false,
conversationId: conversationId,
deviceId: this.deviceId,
body: body,
});
const newMessages = [...this.allMessages];
const indexOfLastMessage = newMessages.findIndex(message => message.messageId == "12");
const lastMessage = newMessages[indexOfLastMessage];
const lastNewMessage = Object.assign(Object.assign({}, lastMessage), { messageId: res.messageId, deliveredToAll: false });
newMessages.splice(indexOfLastMessage, 1, lastNewMessage);
this.updateAllMessages(newMessages);
}
catch (error) {
console.log(error, 'postMessages error for text');
}
finally {
this.changeMessageSendingState(false);
}
this.inputKey++;
}
/////
else if (this.attachmentDetails) {
this.changeMessageSendingState(true);
const mediaId = this.attachmentDetails.lastModified + '';
let mediaType;
const fileType = this.attachmentDetails.type;
if (fileType.startsWith('image/')) {
mediaType = 0;
}
else if (fileType.startsWith('video/')) {
mediaType = 1;
}
else if (fileType.startsWith('audio/')) {
mediaType = 2;
}
else {
mediaType = 3;
}
const attachments = [
{
nameWithExtension: this.attachmentDetails.name,
mediaType: mediaType,
mediaId: mediaId,
mimeType: this.attachmentDetails.type,
size: this.attachmentDetails.size,
file: this.attachmentDetails,
},
];
//
this.updateAllMessages([
...this.allMessages,
{
body: '',
messageId: '12',
deliveredToAll: 'pending',
senderId: this.userMetaData.userId,
sentAt: Date.now(),
attachments: [{ mediaUrl: this.imagePreviewSrc || this.videoPreviewSrc || this.pdfPreviewSrc, mimeType: this.attachmentDetails.type }],
},
]);
this.pdfPreviewSrc = '';
this.videoPreviewSrc = '';
this.imagePreviewSrc = '';
this.messageBody = '';
//
const payLoadForPutApi = this.attachmentDetails;
this.attachmentDetails = null;
try {
const res = await ChatSDK.getInstance().message.postMessagesPresignedurls({ conversationId: conversationId, attachments: attachments });
if (res === null || res === void 0 ? void 0 : res.presignedUrls) {
const mediaId = (_b = (_a = res === null || res === void 0 ? void 0 : res.presignedUrls) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.mediaId;
const mediaUrl = (_d = (_c = res === null || res === void 0 ? void 0 : res.presignedUrls) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.mediaUrl;
const thumbnailUrl = (_f = (_e = res === null || res === void 0 ? void 0 : res.presignedUrls) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.thumbnailUrl;
const attachmentPayload = attachments === null || attachments === void 0 ? void 0 : attachments[0];
const fileExtensionType = attachmentPayload === null || attachmentPayload === void 0 ? void 0 : attachmentPayload.mimeType.split('/')[1];
const newPayload = {
mediaId: mediaId,
mediaUrl: mediaUrl,
thumbnailUrl: thumbnailUrl,
attachmentType: 0,
mimeType: attachmentPayload.mimeType,
name: attachmentPayload.nameWithExtension,
extension: fileExtensionType,
size: attachmentPayload.size,
};
const mediaPresignedUrl = res.presignedUrls[0].mediaPresignedUrl;
try {
await fetch(mediaPresignedUrl, {
method: 'PUT',
body: payLoadForPutApi,
headers: {
'Content-Type': fileType,
},
});
try {
const res = await ChatSDK.getInstance().message.postMessages({
showInConversation: true,
messageType: 0,
encrypted: false,
conversationId,
body: 'attachment',
// @ts-expect-error
attachments: [newPayload],
deviceId: this.deviceId,
});
const newMessages = [...this.allMessages];
const indexOfLastMessage = newMessages.findIndex(message => message.messageId == "12");
const lastMessage = newMessages[indexOfLastMessage];
const lastNewMessage = Object.assign(Object.assign({}, lastMessage), { messageId: res.messageId, deliveredToAll: false });
newMessages.splice(indexOfLastMessage, 1, lastNewMessage);
this.updateAllMessages(newMessages);
}
catch (error) {
console.log(error, 'postMessages error for media');
}
}
catch (error) {
console.log(error, 'error for verify media in put request');
}
}
}
catch (error) {
console.log(error, 'Error while uploading the media for Presignedurls');
}
finally {
this.changeMessageSendingState(false);
}
this.inputKey++;
}
};
this.handleEnterPress = (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
this.handleSendMessage();
}
};
this.messageBody = '';
this.isDark = undefined;
this.conversationId = undefined;
this.userMetaData = undefined;
this.refetchMessages = undefined;
this.changeMessageSendingState = undefined;
this.changeScrollToBottomState = undefined;
this.updateAllMessages = undefined;
this.allMessages = undefined;
this.attachmentDetails = null;
this.deviceId = '';
this.imagePreviewSrc = '';
this.videoPreviewSrc = '';
this.pdfPreviewSrc = '';
this.inputKey = 0;
}
async componentWillLoad() {
const deviceId = await getDeviceID();
this.deviceId = deviceId;
}
componentDidLoad() {
document.addEventListener('keydown', this.handleEnterPress);
}
render() {
const contentType = this.attachmentDetails ? this.attachmentDetails.type.split('/')[0] : '';
const fileName = this.attachmentDetails ? this.attachmentDetails.name : '';
return (h("div", { key: '6bfdccb972d103026702f670537957cdaadada93' }, this.attachmentDetails && (h("attachment-preview", { key: '91e5d538b27da828702582583ce003e1299108be', onClose: () => (this.attachmentDetails = null), width: "150px", height: "150px", bgColor: "#EFF1FA", padding: "3px", margin: "10px 0 0 0", contentType: contentType, content: contentType === 'image' ? this.imagePreviewSrc : contentType === 'video' ? this.videoPreviewSrc : fileName })), h("my-test-footer", { key: this.inputKey, inputValue: this.messageBody, onFileUploaded: this.handleFileUpload, "oninput-change": this.handleInputChange, onSendClick: this.handleSendMessage, bgColor: 'var(--chat-footer-bg)', inputBgColor: 'var(--chat-footer-input-bg)', inputFontColor: 'var(--chat-footer-input-text)', inputContainerBorderColor: 'var(--chat-footer-input-border)', attachmentIconColor: 'var(--chat-footer-attachment-icon)' })));
}
static get is() { return "chat-footer"; }
static get encapsulation() { return "shadow"; }
static get properties() {
return {
"isDark": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": true,
"docs": {
"tags": [],
"text": ""
},
"attribute": "is-dark",
"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
},
"userMetaData": {
"type": "any",
"mutable": false,
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"attribute": "user-meta-data",
"reflect": false
},
"refetchMessages": {
"type": "unknown",
"mutable": false,
"complexType": {
"original": "() => void",
"resolved": "() => void",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
}
},
"changeMessageSendingState": {
"type": "unknown",
"mutable": false,
"complexType": {
"original": "(newState: boolean) => void",
"resolved": "(newState: boolean) => void",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
}
},
"changeScrollToBottomState": {
"type": "unknown",
"mutable": false,
"complexType": {
"original": "(newState: boolean) => void",
"resolved": "(newState: boolean) => void",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
}
},
"updateAllMessages": {
"type": "unknown",
"mutable": false,
"complexType": {
"original": "(newMessages: any) => void",
"resolved": "(newMessages: any) => void",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
}
},
"allMessages": {
"type": "any",
"mutable": false,
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"attribute": "all-messages",
"reflect": false
}
};
}
static get states() {
return {
"messageBody": {},
"attachmentDetails": {},
"deviceId": {},
"imagePreviewSrc": {},
"videoPreviewSrc": {},
"pdfPreviewSrc": {},
"inputKey": {}
};
}
}
export { ChatFooter };
//# sourceMappingURL=ChatFooter.js.map