control chat with state

This commit is contained in:
Phillip Lang Martinez 2022-12-08 20:21:12 -05:00
parent 6e4e171257
commit f980196988
3 changed files with 70 additions and 40 deletions

View File

@ -14,6 +14,7 @@ class ChatHead extends LitElement {
iconName: { type: String }, iconName: { type: String },
activeChatHeadUrl: { type: String }, activeChatHeadUrl: { type: String },
isImageLoaded: { type: Boolean }, isImageLoaded: { type: Boolean },
setActiveChatHeadUrl: {attribute: false}
} }
} }
@ -116,8 +117,6 @@ class ChatHead extends LitElement {
} }
return html` return html`
<li @click=${() => this.getUrl(this.chatInfo.url)} class="clearfix ${this.activeChatHeadUrl === this.chatInfo.url ? 'active' : ''}"> <li @click=${() => this.getUrl(this.chatInfo.url)} class="clearfix ${this.activeChatHeadUrl === this.chatInfo.url ? 'active' : ''}">
${this.isImageLoaded ? html`${avatarImg}` : html`` } ${this.isImageLoaded ? html`${avatarImg}` : html`` }
@ -150,8 +149,19 @@ class ChatHead extends LitElement {
parentEpml.imReady() parentEpml.imReady()
} }
shouldUpdate(changedProperties) {
if(changedProperties.has('activeChatHeadUrl')){
return true
}
if(changedProperties.has('chatInfo')){
return true
}
return false
}
getUrl(chatUrl) { getUrl(chatUrl) {
this.onPageNavigation(`/app/q-chat/${chatUrl}`) this.setActiveChatHeadUrl(chatUrl)
} }
onPageNavigation(pageUrl) { onPageNavigation(pageUrl) {

View File

@ -67,7 +67,8 @@ class ChatPage extends LitElement {
userLanguage: { type: String }, userLanguage: { type: String },
lastMessageRefVisible: { type: Boolean }, lastMessageRefVisible: { type: Boolean },
isLoadingOldMessages: {type: Boolean}, isLoadingOldMessages: {type: Boolean},
isEditMessageOpen: { type: Boolean } isEditMessageOpen: { type: Boolean },
webSocket: {attribute: false}
} }
} }
@ -746,13 +747,11 @@ class ChatPage extends LitElement {
this.initChatEditor(); this.initChatEditor();
} }
async firstUpdated() { async initUpdate(){
window.addEventListener('storage', () => { if(this.webSocket){
const checkLanguage = localStorage.getItem('qortalLanguage'); this.webSocket.close()
use(checkLanguage); this.webSocket= ''
this.userLanguage = checkLanguage; }
})
const getAddressPublicKey = () => { const getAddressPublicKey = () => {
parentEpml.request('apiCall', { parentEpml.request('apiCall', {
@ -794,6 +793,16 @@ class ChatPage extends LitElement {
// this.initChatEditor(); // this.initChatEditor();
}, 100) }, 100)
}
async firstUpdated() {
window.addEventListener('storage', () => {
const checkLanguage = localStorage.getItem('qortalLanguage');
use(checkLanguage);
this.userLanguage = checkLanguage;
})
parentEpml.ready().then(() => { parentEpml.ready().then(() => {
parentEpml.subscribe('selected_address', async selectedAddress => { parentEpml.subscribe('selected_address', async selectedAddress => {
this.selectedAddress = {} this.selectedAddress = {}
@ -817,10 +826,11 @@ class ChatPage extends LitElement {
}) })
}) })
parentEpml.imReady(); parentEpml.imReady();
await this.initUpdate()
} }
async updated(changedProperties) { async updated(changedProperties) {
if (changedProperties && changedProperties.has('userLanguage')) { if (changedProperties && changedProperties.has('userLanguage')) {
const userLang = changedProperties.get('userLanguage') const userLang = changedProperties.get('userLanguage')
@ -830,6 +840,10 @@ class ChatPage extends LitElement {
} }
} }
if (changedProperties && changedProperties.has('chatId') && changedProperties.get('chatId')) {
await this.initUpdate()
}
} }
async renderPlaceholder() { async renderPlaceholder() {
@ -1151,22 +1165,22 @@ class ChatPage extends LitElement {
directSocketLink = `ws://${nodeUrl}/websockets/chat/messages?involving=${window.parent.reduxStore.getState().app.selectedAddress.address}&involving=${cid}`; directSocketLink = `ws://${nodeUrl}/websockets/chat/messages?involving=${window.parent.reduxStore.getState().app.selectedAddress.address}&involving=${cid}`;
} }
const directSocket = new WebSocket(directSocketLink); this.webSocket = new WebSocket(directSocketLink);
// Open Connection // Open Connection
directSocket.onopen = () => { this.webSocket.onopen = () => {
setTimeout(pingDirectSocket, 50) setTimeout(pingDirectSocket, 50)
} }
// Message Event // Message Event
directSocket.onmessage = async (e) => { this.webSocket.onmessage = async (e) => {
if (initial === 0) { if (initial === 0) {
const isReceipient = this.chatId.includes('direct') const isReceipient = this.chatId.includes('direct')
// commented out code= localstorage persistance
const chatReference1 = isReceipient ? 'direct' : 'group'; // const chatReference1 = isReceipient ? 'direct' : 'group';
const chatReference2 = this.chatId.split('/')[1]; // const chatReference2 = this.chatId.split('/')[1];
// const cachedData = await messagesCache.getItem(`${chatReference1}-${chatReference2}`); // const cachedData = await messagesCache.getItem(`${chatReference1}-${chatReference2}`);
const cachedData = null const cachedData = null
let getInitialMessages = [] let getInitialMessages = []
@ -1199,17 +1213,17 @@ class ChatPage extends LitElement {
} }
// Closed Event // Closed Event
directSocket.onclose = () => { this.webSocket.onclose = () => {
clearTimeout(directSocketTimeout) clearTimeout(directSocketTimeout)
} }
// Error Event // Error Event
directSocket.onerror = (e) => { this.webSocket.onerror = (e) => {
clearTimeout(directSocketTimeout) clearTimeout(directSocketTimeout)
} }
const pingDirectSocket = () => { const pingDirectSocket = () => {
directSocket.send('ping') this.webSocket.send('ping')
directSocketTimeout = setTimeout(pingDirectSocket, 295000) directSocketTimeout = setTimeout(pingDirectSocket, 295000)
} }
@ -1237,16 +1251,16 @@ class ChatPage extends LitElement {
groupSocketLink = `ws://${nodeUrl}/websockets/chat/messages?txGroupId=${groupId}`; groupSocketLink = `ws://${nodeUrl}/websockets/chat/messages?txGroupId=${groupId}`;
} }
const groupSocket = new WebSocket(groupSocketLink); this.webSocket = new WebSocket(groupSocketLink);
// Open Connection // Open Connection
groupSocket.onopen = () => { this.webSocket.onopen = () => {
setTimeout(pingGroupSocket, 50) setTimeout(pingGroupSocket, 50)
} }
// Message Event // Message Event
groupSocket.onmessage = async (e) => { this.webSocket.onmessage = async (e) => {
if (initial === 0) { if (initial === 0) {
const isGroup = this.chatId.includes('group') const isGroup = this.chatId.includes('group')
@ -1288,17 +1302,17 @@ class ChatPage extends LitElement {
} }
// Closed Event // Closed Event
groupSocket.onclose = () => { this.webSocket.onclose = () => {
clearTimeout(groupSocketTimeout) clearTimeout(groupSocketTimeout)
} }
// Error Event // Error Event
groupSocket.onerror = (e) => { this.webSocket.onerror = (e) => {
clearTimeout(groupSocketTimeout) clearTimeout(groupSocketTimeout)
} }
const pingGroupSocket = () => { const pingGroupSocket = () => {
groupSocket.send('ping') this.webSocket.send('ping')
groupSocketTimeout = setTimeout(pingGroupSocket, 295000) groupSocketTimeout = setTimeout(pingGroupSocket, 295000)
} }

View File

@ -34,7 +34,8 @@ class Chat extends LitElement {
balance: { type: Number }, balance: { type: Number },
theme: { type: String, reflect: true }, theme: { type: String, reflect: true },
blockedUsers: { type: Array }, blockedUsers: { type: Array },
blockedUserList: { type: Array } blockedUserList: { type: Array },
activeChatHeadUrl: {type: String}
} }
} }
@ -324,6 +325,13 @@ class Chat extends LitElement {
this.theme = localStorage.getItem('qortalTheme') ? localStorage.getItem('qortalTheme') : 'light' this.theme = localStorage.getItem('qortalTheme') ? localStorage.getItem('qortalTheme') : 'light'
this.blockedUsers = [] this.blockedUsers = []
this.blockedUserList = [] this.blockedUserList = []
this.activeChatHeadUrl = ''
}
setActiveChatHeadUrl(url){
this.activeChatHeadUrl = url
} }
render() { render() {
@ -349,7 +357,8 @@ class Chat extends LitElement {
<span>${translate("chatpage.cchange5")} <mwc-icon style="font-size: 16px; vertical-align: bottom;">keyboard_arrow_down</mwc-icon></span> <span>${translate("chatpage.cchange5")} <mwc-icon style="font-size: 16px; vertical-align: bottom;">keyboard_arrow_down</mwc-icon></span>
</div> </div>
<div class="chat-history"> <div class="chat-history">
${window.parent.location.pathname !== "/app/q-chat" ? html`${this.renderChatPage(this.chatId)}` : html`${this.renderChatWelcomePage()}`}
${window.parent.location.pathname !== "/app/q-chat" || this.activeChatHeadUrl ? html`${this.renderChatPage(this.chatId)}` : html`${this.renderChatWelcomePage()}`}
</div> </div>
</div> </div>
@ -416,21 +425,15 @@ class Chat extends LitElement {
} }
firstUpdated() { firstUpdated() {
this.changeLanguage() this.changeLanguage()
this.changeTheme() this.changeTheme()
this.getChatBlockedList() this.getChatBlockedList()
this.getLocalBlockedList() this.getLocalBlockedList()
setInterval(() => {
this.blockedUserList = JSON.parse(localStorage.getItem("ChatBlockedAddresses") || "[]")
}, 1000)
const getBlockedUsers = async () => { const getBlockedUsers = async () => {
let blockedUsers = await parentEpml.request('apiCall', { let blockedUsers = await parentEpml.request('apiCall', {
url: `/lists/blockedAddresses?apiKey=${this.getApiKey()}` url: `/lists/blockedAddresses?apiKey=${this.getApiKey()}`
}) })
this.blockedUsers = blockedUsers this.blockedUsers = blockedUsers
setTimeout(getBlockedUsers, 60000) setTimeout(getBlockedUsers, 60000)
} }
@ -455,7 +458,7 @@ class Chat extends LitElement {
const runFunctionsAfterPageLoad = () => { const runFunctionsAfterPageLoad = () => {
// Functions to exec after render while waiting for page info... // Functions to exec after render while waiting for page info...
getDataFromURL() // getDataFromURL()
try { try {
let key = `${window.parent.reduxStore.getState().app.selectedAddress.address.substr(0, 10)}_chat-heads` let key = `${window.parent.reduxStore.getState().app.selectedAddress.address.substr(0, 10)}_chat-heads`
@ -572,6 +575,8 @@ class Chat extends LitElement {
hidelist.push(item) hidelist.push(item)
}) })
localStorage.setItem("MessageBlockedAddresses", JSON.stringify(hidelist)) localStorage.setItem("MessageBlockedAddresses", JSON.stringify(hidelist))
this.blockedUserList = hidelist
}) })
} }
@ -604,6 +609,7 @@ class Chat extends LitElement {
obj.push(noName) obj.push(noName)
} }
localStorage.setItem("ChatBlockedAddresses", JSON.stringify(obj)) localStorage.setItem("ChatBlockedAddresses", JSON.stringify(obj))
this.blockedUserList = JSON.parse(localStorage.getItem("ChatBlockedAddresses") || "[]")
}) })
}) })
}) })
@ -681,20 +687,20 @@ class Chat extends LitElement {
let tempUrl = document.location.href let tempUrl = document.location.href
let splitedUrl = decodeURI(tempUrl).split('?') let splitedUrl = decodeURI(tempUrl).split('?')
let activeChatHeadUrl = splitedUrl[1] === undefined ? '' : splitedUrl[1] // let activeChatHeadUrl = splitedUrl[1] === undefined ? '' : splitedUrl[1]
return chatHeadArr.map(eachChatHead => { return chatHeadArr.map(eachChatHead => {
return html`<chat-head activeChatHeadUrl=${activeChatHeadUrl} chatInfo=${JSON.stringify(eachChatHead)}></chat-head>` return html`<chat-head activeChatHeadUrl=${this.activeChatHeadUrl} .setActiveChatHeadUrl=${(val)=> this.setActiveChatHeadUrl(val)} chatInfo=${JSON.stringify(eachChatHead)}></chat-head>`
}) })
} }
renderChatPage(chatId) { renderChatPage(chatId) {
// Check for the chat ID from and render chat messages // Check for the chat ID from and render chat messages
// Else render Welcome to Q-CHat // Else render Welcome to Q-CHat
// TODO: DONE: Do the above in the ChatPage // TODO: DONE: Do the above in the ChatPage
return html`<chat-page .hideNewMesssageBar=${this.hideNewMesssageBar} .showNewMesssageBar=${this.showNewMesssageBar} myAddress=${window.parent.reduxStore.getState().app.selectedAddress.address} chatId=${this.activeChatHeadUrl}></chat-page>`
return html`<chat-page .hideNewMesssageBar=${this.hideNewMesssageBar} .showNewMesssageBar=${this.showNewMesssageBar} myAddress=${window.parent.reduxStore.getState().app.selectedAddress.address} chatId=${chatId}></chat-page>`
} }
setChatHeads(chatObj) { setChatHeads(chatObj) {