How to get activate particular conversation chat - javascript

I'm using wschat wordpress plugin. I'm passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I'm passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will be shown below:
admin_chat.js:
import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '#joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'
jQuery(document).ready(function() {
const wrapper = jQuery('.wschat-wrapper');
if (wrapper.length === 0) {
return;
}
const CONVERSATION_TEMPLATE = `
<div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
<img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
<div class="text">
<h6>{{NAME}}</h6>
<p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
</div>
<span class="time small d-none">{{TIMESTAMP}}</span>
<span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
</div>
<hr>`;
const CHAT_BUBBLE_TEMPLATE = `
<div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
<div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
<div class="chat-bubble chat-bubble--{{POS}}">
{{CONTENT}}
</div>
<span class="time">{{TIMESTAMP}}</span>
</div>
</div>`;
const CONVERSATION_TEMPLATE_DEFAULTS = {
'{{CONVERSATION_ID}}': '',
'{{LAST_MESSAGE}}': 'left',
'{{TIMESTAMP}}': '',
'{{NAME}}': '',
};
const BUBBLE_TEMPLATE_DEFAULTS = {
'{{OFFSET}}': '',
'{{POS}}': 'left',
'{{CONTENT}}': '',
'{{TIMESTAMP}}': '',
'{{MESSAGE_ID}}': '',
};
jQuery.ajaxSetup({
data: {
wschat_ajax_nonce: wschat_ajax_obj.nonce
}
});
var chat = new WSChat(jQuery('.wschat-wrapper'), {
connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
api: {
endpoint: wschat_ajax_obj.ajax_url,
interval: 3000,
wschat_ajax_nonce: wschat_ajax_obj.nonce,
pusher: {
key: wschat_ajax_obj.settings.pusher.app_key,
cluster: wschat_ajax_obj.settings.pusher.cluster,
}
},
alert: {
url: wschat_ajax_obj.settings.alert_tone_url
},
header: {
status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
}
});
if (wschat_ajax_obj.settings) {
for(let key in wschat_ajax_obj.settings.colors) {
key && chat.$el.get(0).style.setProperty(key, '#' +wschat_ajax_obj.settings.colors[key]);
}
}
setInterval(() => {
chat.connector.start_conversation();
}, 5000);
const chat_panel = chat.$el.find('.chat-panel');
const conversation_panel = chat.$el.find('.conversation-list');
const chat_panel_header = chat.$el.find('.chat-panel-header');
const chat_tray_box = chat.$el.find('.chat-box-tray');
const message_input = jQuery('#wschat_message_input');
const MESSAGE_INFO = {
min: 0,
max: 0,
};
let PAST_REQUEST_IS_PENDING = false;
let SCROLL_PAUSED = false;
let DISABLE_SCROLL_LOCK = false;
const SCROLL_OFFSET = 100;
const replaceConversation = (conversation) => {
let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
if (item.length === 0 ) {
return false;
}
item.find('.time').text(conversation.updated_at);
item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
item.find('.unread-count').text(conversation.unread_count || '');
if (conversation.is_user_online) {
item.addClass('online');
} else {
item.removeClass('online');
}
return true;
};
const sortConversation = () => {
const new_conversation_panel = conversation_panel.clone();
const items = [];
new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
items.push(item);
});
items.sort((a, b) => {
let timestamp1 = jQuery(a).find('.time').html();
let timestamp2 = jQuery(b).find('.time').html();
return strToDate(timestamp2) - strToDate(timestamp1);
});
new_conversation_panel.html('');
items.forEach((item) => {
new_conversation_panel.append(item);
});
conversation_panel.html(new_conversation_panel.html());
};
const strToDate = (timestamp) => {
let [date1, time1] = timestamp.split(' ');
date1 = date1.split('-');
time1 = time1.split(':');
return parseInt(date1.join('') + time1.join(''));
};
const showNoConversation = () => {
const no_conversation_alert = jQuery('.no-conversation-alert');
conversation_panel.append(no_conversation_alert.removeClass('d-none'));
}
chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
showNoConversation();
});
chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {
conversations.forEach(conversation => {
if (replaceConversation(conversation)) {
return;
}
CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';
let row_template = CONVERSATION_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);
row_template = jQuery(row_template);
if (conversation.is_user_online) {
row_template = row_template.addClass('online');
}
if (conversation.user && conversation.user.meta.avatar) {
row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
}
conversation_panel.append(row_template);
});
sortConversation();
setTimeout(() => {
let activeItem = conversation_panel.find('.active[data-conversation-id]').length
activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
}, 1000);
});
chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
data.user &&
chat_panel_header.find('.username').text(data.user.meta.name);
let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);
chat_panel_header.parent().removeClass('d-none')
info.find('.name').html(data.user.meta.name);
info.find('.browser').html(data.user.meta.browser);
info.find('.os').html(data.user.meta.os);
info.find('.device').html(data.user.meta.device);
info.find('.url').html(data.user.meta.current_url);
message_input.focus();
MESSAGE_INFO.min = 0;
MESSAGE_INFO.max = 0;
DISABLE_SCROLL_LOCK = true;
resizeChat();
setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
});
chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
for (let i = 0; i < data.messages.length; i++) {
let row = data.messages[i];
if (row.is_agent === true) {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
} else {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
}
BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);
let row_template = CHAT_BUBBLE_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);
if (MESSAGE_INFO.min === 0) {
chat_panel.append('<span data-message-id="0"></span>');
}
if (MESSAGE_INFO.min > row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
MESSAGE_INFO.min = row.id;
}
if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
MESSAGE_INFO.max = row.id;
scrollIfNotPaused();
}
if (MESSAGE_INFO.min === 0) {
scrollIfNotPaused();
}
MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
}
if (DISABLE_SCROLL_LOCK === true) {
scrollIfNotPaused();
}
});
chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
let drawer = chat_panel_header.find('.friend-drawer');
let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
let row_unread_count = row_template.find('.unread-count');
let header_unread_count = chat_panel_header.find('.unread-count');
chat_panel_header.find('.status').text(data.status);
header_unread_count.text(data.unread_count);
row_unread_count.text(data.unread_count || '');
if (data.unread_count) {
header_unread_count.removeClass('d-none');
} else {
header_unread_count.addClass('d-none');
}
if (data.is_online) {
drawer.addClass('online');
row_template.addClass('online');
} else {
drawer.removeClass('online');
row_template.removeClass('online');
}
});
const scrollIfNotPaused = () => {
if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
}
}
const send_btn = jQuery('#wschat_send_message').on('click', function() {
let msg = message_input.val();
if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
return false;
}
chat.sendMessage({
// Type is text by default now, it needs to changed based on the selection content
wschat_ajax_nonce: wschat_ajax_obj.nonce,
type: 'text',
'content[text]': message_input.val()
});
message_input.val('').focus();
});
message_input.keyup(function(e) {
e.key === 'Enter' && send_btn.click();
});
message_input.on('focus', function() {
let unread_count = chat_panel_header.find('.unread-count').text();
if (parseInt(unread_count) > 0) {
chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
}
});
chat_panel_header.on('click', '.user-meta-info-toggle', function () {
chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
});
conversation_panel.on('click', '[data-conversation-id]', function() {
chat_panel.html('');
let item = jQuery(this);
let converssation_id = item.data('conversation-id');
conversation_panel.find('[data-conversation-id]').removeClass('active');
item.addClass('active')
chat.connector.join_conversation(converssation_id);
});
chat_panel.on('scroll', function () {
if (DISABLE_SCROLL_LOCK) {
SCROLL_PAUSED = false;
return;
}
if (this.scrollTop < SCROLL_OFFSET) {
if (PAST_REQUEST_IS_PENDING === false) {
PAST_REQUEST_IS_PENDING = true;
chat.connector.get_messages({
after: 0,
before: MESSAGE_INFO.min
});
setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
}
}
if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
SCROLL_PAUSED = false;
} else {
SCROLL_PAUSED = true;
}
});
const resizeChat = () => {
const window_height = jQuery(window).height() - chat.$el.offset().top;
const height = window_height - (
chat_panel_header.height()*2 + chat_tray_box.height()
);
conversation_panel.css({
'min-height': height + 'px'
});
chat_panel.css({
'min-height': height + 'px'
});
};
jQuery(window).resize(() => resizeChat());
resizeChat();
const emojiPicker = document.getElementById('wschat_emoji_picker');
const emoji = new EmojiButton({
style: 'twemoji',
rootElement: emojiPicker.parentElement,
position: 'top'
});
emojiPicker.addEventListener('click', function() {
emoji.togglePicker();
});
emoji.on('emoji', function(selection) {
console.log(selection)
message_input.val(message_input.val() + selection.emoji).focus();
setTimeout(() => message_input.focus(), 500)
});
// Attachment toggler
chat.$el.find('#attachment_picker').click(function (e) {
e.preventDefault();
chat.$el.find('.attachment-list').toggleClass('show d-none');
});
chat.$el.find('.attachment-list').on('click','button', function () {
chat.$el.find('#attachment_picker').click();
});
});
Can someone help me on this? How to activate the conversation by getting id from url?
Also, i don't know what type of js they are used can any one let me know?

Related

How to get id from link using js

I'm using wschat wordpress plugin. I'm passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I'm passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will bw:
admin_chat.js:
import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '#joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'
jQuery(document).ready(function() {
const wrapper = jQuery('.wschat-wrapper');
if (wrapper.length === 0) {
return;
}
const CONVERSATION_TEMPLATE = `
<div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
<img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
<div class="text">
<h6>{{NAME}}</h6>
<p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
</div>
<span class="time small d-none">{{TIMESTAMP}}</span>
<span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
</div>
<hr>`;
const CHAT_BUBBLE_TEMPLATE = `
<div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
<div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
<div class="chat-bubble chat-bubble--{{POS}}">
{{CONTENT}}
</div>
<span class="time">{{TIMESTAMP}}</span>
</div>
</div>`;
const CONVERSATION_TEMPLATE_DEFAULTS = {
'{{CONVERSATION_ID}}': '',
'{{LAST_MESSAGE}}': 'left',
'{{TIMESTAMP}}': '',
'{{NAME}}': '',
};
const BUBBLE_TEMPLATE_DEFAULTS = {
'{{OFFSET}}': '',
'{{POS}}': 'left',
'{{CONTENT}}': '',
'{{TIMESTAMP}}': '',
'{{MESSAGE_ID}}': '',
};
jQuery.ajaxSetup({
data: {
wschat_ajax_nonce: wschat_ajax_obj.nonce
}
});
var chat = new WSChat(jQuery('.wschat-wrapper'), {
connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
api: {
endpoint: wschat_ajax_obj.ajax_url,
interval: 3000,
wschat_ajax_nonce: wschat_ajax_obj.nonce,
pusher: {
key: wschat_ajax_obj.settings.pusher.app_key,
cluster: wschat_ajax_obj.settings.pusher.cluster,
}
},
alert: {
url: wschat_ajax_obj.settings.alert_tone_url
},
header: {
status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
}
});
if (wschat_ajax_obj.settings) {
for(let key in wschat_ajax_obj.settings.colors) {
key && chat.$el.get(0).style.setProperty(key, '#' +wschat_ajax_obj.settings.colors[key]);
}
}
setInterval(() => {
chat.connector.start_conversation();
}, 5000);
const chat_panel = chat.$el.find('.chat-panel');
const conversation_panel = chat.$el.find('.conversation-list');
const chat_panel_header = chat.$el.find('.chat-panel-header');
const chat_tray_box = chat.$el.find('.chat-box-tray');
const message_input = jQuery('#wschat_message_input');
const MESSAGE_INFO = {
min: 0,
max: 0,
};
let PAST_REQUEST_IS_PENDING = false;
let SCROLL_PAUSED = false;
let DISABLE_SCROLL_LOCK = false;
const SCROLL_OFFSET = 100;
const replaceConversation = (conversation) => {
let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
if (item.length === 0 ) {
return false;
}
item.find('.time').text(conversation.updated_at);
item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
item.find('.unread-count').text(conversation.unread_count || '');
if (conversation.is_user_online) {
item.addClass('online');
} else {
item.removeClass('online');
}
return true;
};
const sortConversation = () => {
const new_conversation_panel = conversation_panel.clone();
const items = [];
new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
items.push(item);
});
items.sort((a, b) => {
let timestamp1 = jQuery(a).find('.time').html();
let timestamp2 = jQuery(b).find('.time').html();
return strToDate(timestamp2) - strToDate(timestamp1);
});
new_conversation_panel.html('');
items.forEach((item) => {
new_conversation_panel.append(item);
});
conversation_panel.html(new_conversation_panel.html());
};
const strToDate = (timestamp) => {
let [date1, time1] = timestamp.split(' ');
date1 = date1.split('-');
time1 = time1.split(':');
return parseInt(date1.join('') + time1.join(''));
};
const showNoConversation = () => {
const no_conversation_alert = jQuery('.no-conversation-alert');
conversation_panel.append(no_conversation_alert.removeClass('d-none'));
}
chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
showNoConversation();
});
chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {
conversations.forEach(conversation => {
if (replaceConversation(conversation)) {
return;
}
CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';
let row_template = CONVERSATION_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);
row_template = jQuery(row_template);
if (conversation.is_user_online) {
row_template = row_template.addClass('online');
}
if (conversation.user && conversation.user.meta.avatar) {
row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
}
conversation_panel.append(row_template);
});
sortConversation();
setTimeout(() => {
let activeItem = conversation_panel.find('.active[data-conversation-id]').length
activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
}, 1000);
});
chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
data.user &&
chat_panel_header.find('.username').text(data.user.meta.name);
let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);
chat_panel_header.parent().removeClass('d-none')
info.find('.name').html(data.user.meta.name);
info.find('.browser').html(data.user.meta.browser);
info.find('.os').html(data.user.meta.os);
info.find('.device').html(data.user.meta.device);
info.find('.url').html(data.user.meta.current_url);
message_input.focus();
MESSAGE_INFO.min = 0;
MESSAGE_INFO.max = 0;
DISABLE_SCROLL_LOCK = true;
resizeChat();
setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
});
chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
for (let i = 0; i < data.messages.length; i++) {
let row = data.messages[i];
if (row.is_agent === true) {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
} else {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
}
BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);
let row_template = CHAT_BUBBLE_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);
if (MESSAGE_INFO.min === 0) {
chat_panel.append('<span data-message-id="0"></span>');
}
if (MESSAGE_INFO.min > row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
MESSAGE_INFO.min = row.id;
}
if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
MESSAGE_INFO.max = row.id;
scrollIfNotPaused();
}
if (MESSAGE_INFO.min === 0) {
scrollIfNotPaused();
}
MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
}
if (DISABLE_SCROLL_LOCK === true) {
scrollIfNotPaused();
}
});
chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
let drawer = chat_panel_header.find('.friend-drawer');
let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
let row_unread_count = row_template.find('.unread-count');
let header_unread_count = chat_panel_header.find('.unread-count');
chat_panel_header.find('.status').text(data.status);
header_unread_count.text(data.unread_count);
row_unread_count.text(data.unread_count || '');
if (data.unread_count) {
header_unread_count.removeClass('d-none');
} else {
header_unread_count.addClass('d-none');
}
if (data.is_online) {
drawer.addClass('online');
row_template.addClass('online');
} else {
drawer.removeClass('online');
row_template.removeClass('online');
}
});
const scrollIfNotPaused = () => {
if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
}
}
const send_btn = jQuery('#wschat_send_message').on('click', function() {
let msg = message_input.val();
if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
return false;
}
chat.sendMessage({
// Type is text by default now, it needs to changed based on the selection content
wschat_ajax_nonce: wschat_ajax_obj.nonce,
type: 'text',
'content[text]': message_input.val()
});
message_input.val('').focus();
});
message_input.keyup(function(e) {
e.key === 'Enter' && send_btn.click();
});
message_input.on('focus', function() {
let unread_count = chat_panel_header.find('.unread-count').text();
if (parseInt(unread_count) > 0) {
chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
}
});
chat_panel_header.on('click', '.user-meta-info-toggle', function () {
chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
});
conversation_panel.on('click', '[data-conversation-id]', function() {
chat_panel.html('');
let item = jQuery(this);
let converssation_id = item.data('conversation-id');
conversation_panel.find('[data-conversation-id]').removeClass('active');
item.addClass('active')
chat.connector.join_conversation(converssation_id);
});
chat_panel.on('scroll', function () {
if (DISABLE_SCROLL_LOCK) {
SCROLL_PAUSED = false;
return;
}
if (this.scrollTop < SCROLL_OFFSET) {
if (PAST_REQUEST_IS_PENDING === false) {
PAST_REQUEST_IS_PENDING = true;
chat.connector.get_messages({
after: 0,
before: MESSAGE_INFO.min
});
setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
}
}
if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
SCROLL_PAUSED = false;
} else {
SCROLL_PAUSED = true;
}
});
const resizeChat = () => {
const window_height = jQuery(window).height() - chat.$el.offset().top;
const height = window_height - (
chat_panel_header.height()*2 + chat_tray_box.height()
);
conversation_panel.css({
'min-height': height + 'px'
});
chat_panel.css({
'min-height': height + 'px'
});
};
jQuery(window).resize(() => resizeChat());
resizeChat();
const emojiPicker = document.getElementById('wschat_emoji_picker');
const emoji = new EmojiButton({
style: 'twemoji',
rootElement: emojiPicker.parentElement,
position: 'top'
});
emojiPicker.addEventListener('click', function() {
emoji.togglePicker();
});
emoji.on('emoji', function(selection) {
console.log(selection)
message_input.val(message_input.val() + selection.emoji).focus();
setTimeout(() => message_input.focus(), 500)
});
// Attachment toggler
chat.$el.find('#attachment_picker').click(function (e) {
e.preventDefault();
chat.$el.find('.attachment-list').toggleClass('show d-none');
});
chat.$el.find('.attachment-list').on('click','button', function () {
chat.$el.find('#attachment_picker').click();
});
});
Can someone help me on this? How to get id using this js file and activate the conversation?
Here is what I used for my project to get URL parameters.
var getParameter = function getParameter(param) {
var pageURL = window.location.search.substring(1), // Get current URL substrings
urlVars = pageURL.split('&'), // Split on all "&" for more than one.
parameterName,
i;
for (i = 0; i < urlVars.length; i++) {
// Get the value of the parameter.
parameterName = urlVars[i].split('=');
// Return the value of the parameter if it has the same name as param
if (parameterName[0] === param) {
return typeof parameterName[1] === undefined ? true : decodeURIComponent(parameterName[1]);
}
}
return false;
};
var cID = getParameter('cid');

How webpack HotModuleReplacementPlugin works and what does it do?

(I'm not good at English, if there is any problem that I did not describe clearly, please remind me to modify),
I often see some questions or articles about why webpack hmr does not work or why my webpack dev server config is invalid or how to config webpack hmr.
But has anyone tried to study the working principle behind webpack hmr in the past, The HotModuleReplacementPlugin.js has nearly 400 lines of code, what it is actually doing, I know he will generate a runtime code to insert into the entry, but I want to know,what does it do by subscribing to these hooks? If anyone knows, can you briefly describe it to me? I am trying to understand him at the moment, but it is a bit difficult with my ability, but I am very interested in webpack, and I will be grateful!!!🌈
ps:
// source code
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers #sokra
*/
"use strict";
const { SyncBailHook } = require("tapable");
const { RawSource } = require("webpack-sources");
const Template = require("./Template");
const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
const ParserHelpers = require("./ParserHelpers");
module.exports = class HotModuleReplacementPlugin {
constructor(options) {
this.options = options || {};
this.multiStep = this.options.multiStep;
this.fullBuildTimeout = this.options.fullBuildTimeout || 200;
this.requestTimeout = this.options.requestTimeout || 10000;
}
apply(compiler) {
const multiStep = this.multiStep;
const fullBuildTimeout = this.fullBuildTimeout;
const requestTimeout = this.requestTimeout;
const hotUpdateChunkFilename =
compiler.options.output.hotUpdateChunkFilename;
const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
console.log("multiStep:",multiStep,"fullBuildTimeout:",fullBuildTimeout,"requestTimeout:",requestTimeout,"hotUpdateChunkFilename:",hotUpdateChunkFilename,"hotUpdateMainFilename:",hotUpdateMainFilename)
compiler.hooks.additionalPass.tapAsync(
"HotModuleReplacementPlugin",
callback => {
console.log("HotModuleReplacementPlugin-compiler hooks additionalPass multiStep",multiStep)
if (multiStep) return setTimeout(callback, fullBuildTimeout);
return callback();
}
);
const addParserPlugins = (parser, parserOptions) => {
parser.hooks.expression
.for("__webpack_hash__")
.tap(
"HotModuleReplacementPlugin",
ParserHelpers.toConstantDependencyWithWebpackRequire(
parser,
"__webpack_require__.h()"
)
);
parser.hooks.evaluateTypeof
.for("__webpack_hash__")
.tap(
"HotModuleReplacementPlugin",
ParserHelpers.evaluateToString("string")
);
parser.hooks.evaluateIdentifier.for("module.hot").tap(
{
name: "HotModuleReplacementPlugin",
before: "NodeStuffPlugin"
},
expr => {
return ParserHelpers.evaluateToIdentifier(
"module.hot",
!!parser.state.compilation.hotUpdateChunkTemplate
)(expr);
}
);
// TODO webpack 5: refactor this, no custom hooks
if (!parser.hooks.hotAcceptCallback) {
parser.hooks.hotAcceptCallback = new SyncBailHook([
"expression",
"requests"
]);
}
if (!parser.hooks.hotAcceptWithoutCallback) {
parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([
"expression",
"requests"
]);
}
parser.hooks.call
.for("module.hot.accept")
.tap("HotModuleReplacementPlugin", expr => {
console.log("HotModuleReplacementPlugin- parser.hooks module.hot.accept expr",JSON.stringify(expr))
if (!parser.state.compilation.hotUpdateChunkTemplate) {
return false;
}
if (expr.arguments.length >= 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
let params = [];
let requests = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params = arg.items.filter(param => param.isString());
}
if (params.length > 0) {
params.forEach((param, idx) => {
const request = param.string;
const dep = new ModuleHotAcceptDependency(request, param.range);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
parser.state.module.addDependency(dep);
requests.push(request);
});
if (expr.arguments.length > 1) {
parser.hooks.hotAcceptCallback.call(
expr.arguments[1],
requests
);
parser.walkExpression(expr.arguments[1]); // other args are ignored
return true;
} else {
parser.hooks.hotAcceptWithoutCallback.call(expr, requests);
return true;
}
}
}
});
parser.hooks.call
.for("module.hot.decline")
.tap("HotModuleReplacementPlugin", expr => {
console.log("HotModuleReplacementPlugin- parser.hooks module.hot.decline expr",JSON.stringify(expr))
if (!parser.state.compilation.hotUpdateChunkTemplate) {
return false;
}
if (expr.arguments.length === 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params = arg.items.filter(param => param.isString());
}
params.forEach((param, idx) => {
const dep = new ModuleHotDeclineDependency(
param.string,
param.range
);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
parser.state.module.addDependency(dep);
});
}
});
parser.hooks.expression
.for("module.hot")
.tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal);
};
compiler.hooks.compilation.tap(
"HotModuleReplacementPlugin",
(compilation, { normalModuleFactory }) => {
const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
if (!hotUpdateChunkTemplate) return;
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotAcceptDependency,
new ModuleHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotDeclineDependency,
new ModuleHotDeclineDependency.Template()
);
compilation.hooks.record.tap(
"HotModuleReplacementPlugin",
(compilation, records) => {
if (records.hash === compilation.hash) return;
records.hash = compilation.hash;
records.moduleHashs = {};
for (const module of compilation.modules) {
const identifier = module.identifier();
records.moduleHashs[identifier] = module.hash;
}
records.chunkHashs = {};
for (const chunk of compilation.chunks) {
records.chunkHashs[chunk.id] = chunk.hash;
}
records.chunkModuleIds = {};
for (const chunk of compilation.chunks) {
records.chunkModuleIds[chunk.id] = Array.from(
chunk.modulesIterable,
m => m.id
);
}
}
);
let initialPass = false;
let recompilation = false;
compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => {
let records = compilation.records;
if (!records) {
initialPass = true;
return;
}
if (!records.hash) initialPass = true;
const preHash = records.preHash || "x";
const prepreHash = records.prepreHash || "x";
if (preHash === compilation.hash) {
recompilation = true;
compilation.modifyHash(prepreHash);
return;
}
records.prepreHash = records.hash || "x";
records.preHash = compilation.hash;
compilation.modifyHash(records.prepreHash);
});
compilation.hooks.shouldGenerateChunkAssets.tap(
"HotModuleReplacementPlugin",
() => {
if (multiStep && !recompilation && !initialPass) return false;
}
);
compilation.hooks.needAdditionalPass.tap(
"HotModuleReplacementPlugin",
() => {
if (multiStep && !recompilation && !initialPass) return true;
}
);
compilation.hooks.additionalChunkAssets.tap(
"HotModuleReplacementPlugin",
() => {
const records = compilation.records;
if (records.hash === compilation.hash) return;
if (
!records.moduleHashs ||
!records.chunkHashs ||
!records.chunkModuleIds
)
return;
for (const module of compilation.modules) {
const identifier = module.identifier();
let hash = module.hash;
module.hotUpdate = records.moduleHashs[identifier] !== hash;
}
const hotUpdateMainContent = {
h: compilation.hash,
c: {}
};
for (const key of Object.keys(records.chunkHashs)) {
const chunkId = isNaN(+key) ? key : +key;
const currentChunk = compilation.chunks.find(
chunk => chunk.id === chunkId
);
if (currentChunk) {
const newModules = currentChunk
.getModules()
.filter(module => module.hotUpdate);
const allModules = new Set();
for (const module of currentChunk.modulesIterable) {
allModules.add(module.id);
}
const removedModules = records.chunkModuleIds[chunkId].filter(
id => !allModules.has(id)
);
if (newModules.length > 0 || removedModules.length > 0) {
const source = hotUpdateChunkTemplate.render(
chunkId,
newModules,
removedModules,
compilation.hash,
compilation.moduleTemplates.javascript,
compilation.dependencyTemplates
);
const filename = compilation.getPath(hotUpdateChunkFilename, {
hash: records.hash,
chunk: currentChunk
});
compilation.additionalChunkAssets.push(filename);
compilation.assets[filename] = source;
hotUpdateMainContent.c[chunkId] = true;
currentChunk.files.push(filename);
compilation.hooks.chunkAsset.call(currentChunk, filename);
}
} else {
hotUpdateMainContent.c[chunkId] = false;
}
}
const source = new RawSource(JSON.stringify(hotUpdateMainContent));
const filename = compilation.getPath(hotUpdateMainFilename, {
hash: records.hash
});
compilation.assets[filename] = source;
}
);
const mainTemplate = compilation.mainTemplate;
mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => {
hash.update("HotMainTemplateDecorator");
});
mainTemplate.hooks.moduleRequire.tap(
"HotModuleReplacementPlugin",
(_, chunk, hash, varModuleId) => {
return `hotCreateRequire(${varModuleId})`;
}
);
mainTemplate.hooks.requireExtensions.tap(
"HotModuleReplacementPlugin",
source => {
const buf = [source];
buf.push("");
buf.push("// __webpack_hash__");
buf.push(
mainTemplate.requireFn +
".h = function() { return hotCurrentHash; };"
);
return Template.asString(buf);
}
);
const needChunkLoadingCode = chunk => {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.chunks.length > 1) return true;
if (chunkGroup.getNumberOfChildren() > 0) return true;
}
return false;
};
mainTemplate.hooks.bootstrap.tap(
"HotModuleReplacementPlugin",
(source, chunk, hash) => {
source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash);
return Template.asString([
source,
"",
hotInitCode
.replace(/\$require\$/g, mainTemplate.requireFn)
.replace(/\$hash\$/g, JSON.stringify(hash))
.replace(/\$requestTimeout\$/g, requestTimeout)
.replace(
/\/\*foreachInstalledChunks\*\//g,
needChunkLoadingCode(chunk)
? "for(var chunkId in installedChunks)"
: `var chunkId = ${JSON.stringify(chunk.id)};`
)
]);
}
);
mainTemplate.hooks.globalHash.tap(
"HotModuleReplacementPlugin",
() => true
);
mainTemplate.hooks.currentHash.tap(
"HotModuleReplacementPlugin",
(_, length) => {
if (isFinite(length)) {
return `hotCurrentHash.substr(0, ${length})`;
} else {
return "hotCurrentHash";
}
}
);
mainTemplate.hooks.moduleObj.tap(
"HotModuleReplacementPlugin",
(source, chunk, hash, varModuleId) => {
return Template.asString([
`${source},`,
`hot: hotCreateModule(${varModuleId}),`,
"parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
"children: []"
]);
}
);
// TODO add HMR support for javascript/esm
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("HotModuleReplacementPlugin", addParserPlugins);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("HotModuleReplacementPlugin", addParserPlugins);
compilation.hooks.normalModuleLoader.tap(
"HotModuleReplacementPlugin",
context => {
context.hot = true;
}
);
}
);
}
};
const hotInitCode = Template.getFunctionContent(
require("./HotModuleReplacement.runtime")
);
console.log("hotInitCode",hotInitCode)

Remove sorting in js

How to remove sorting from this script part:
getFirstAvailablePeriod() {
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = sortedPeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return sortedPeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
return period.sort - prev.sort;
}).filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},
This script part reorder Periods from API. Plaese help me to remove rorting Periods from this script. My JS knownleadge is very bad.
Thanks
In getFirstAvailablePeriod instead of
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
try this
const sortedPeriods = [...this.periods].sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
And to remove all sortings, delete sorting in getPeroids
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
Remove this part
.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
Removed sorting. Give it a try.
getFirstAvailablePeriod() {
const availablePeriods = this.periods.filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = availablePeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return availablePeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},

how to wait for function to execute and then go next javascript

I have a 2 function,
inside my runConfigComplianceDeviceOnClick I am calling the getDeviceRunningCompliance function to get some other data and based on both the results I have to return an object,
But What I am observing my data from the getDeviceRunningCompliance (Axios request to get data) function is not returned and it executes next lines,
but when I see in the console value is updated,
How to handle this case,
how to wait for the function to execute and then go next javascript? wanted to deal with asynchronous data then proceed further to the next lines...
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
let some = getDeviceRunningCompliance(selectedDevices);
console.log("getDeviceRunningCompliance some ", some)
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some)
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss)
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
};
const getDeviceRunningCompliance = (selectedDevices) => {
let self = this;
let deviceRunningComplaince = [];
selectedDevices.forEach((val, index) => {
let obj = {};
getComplianceDetails(val.id).then(data => {
const complianceDetailsData = data;
if (complianceDetailsData) {
// this.setState({
// complianceDetailsData: data
// });
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
deviceRunningComplaince.push(obj);
// return cardStatus;
}
});
// deviceRunningComplaince.push(obj);
});
return deviceRunningComplaince;
};
This is how I solved this issue. Please comment if we can do this better.
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
getDeviceRunningCompliance(selectedDevices).then(function(some) {
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some);
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss);
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
});
};
const getDeviceRunningCompliance = selectedDevices => {
let promiseData = selectedDevices.map((val, index) => {
return getComplianceDetails(val.id).then(data => {
let obj = {};
const complianceDetailsData = data;
if (complianceDetailsData) {
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
return obj;
}
});
});
return Promise.all(promiseData);
};

Cant access method to download Image

I'm trying to call a method to download an image of map, but I dont know how to do it waiting to
If only I use this part of code I can download perfectly an image
handleGetImage = () => {
this.setState({ imageButtonDisabled: true, cancelButtonDisabled: true, isLoading: true });
this.checkIfStatusEnd();
if (this.state.radioArea === true) {
this.hideLayerArea();
var size = /** #type {ol.Size} */ (this.map.getSize());
this.map.getView().setCenter(this.state.center);
this.map.getView().fit(this.state.extent, size);
}
window.setTimeout( () => {
var canvas = document.getElementsByTagName("canvas")[0];
this.map.once('precompose', (event) => {
this.setDPI(canvas,300);
});
this.map.once('postcompose', (event) => {
var canvas = event.context.canvas;
canvas.toBlob( (blob) => {
this.showLayerArea();
FileSaver.saveAs(blob, "map.png");
this.setState({ imageButtonDisabled: false, cancelButtonDisabled: false, isLoading: false });
// this.props.closePopup();
});
});
}, 400 );
}
setDPI = (canvas, dpi) => {
var scaleFactor = dpi / 96;
canvas.width = Math.ceil(canvas.width * scaleFactor);
canvas.height = Math.ceil(canvas.height * scaleFactor);
var ctx=canvas.getContext("2d");
ctx.scale(scaleFactor, scaleFactor);
}
But when I try to call method downloadImage inside hide method dont work. How can call correctly the method?
hide method is called when map rendering is finished.
I dont know a lot javascript, I'm learning.. could someone explain me or how make a better implementation that when this.loading === this.loaded call the method downloadImage? with a callback or something else?
Thanks
handleGetImage = () => {
this.setState({ imageButtonDisabled: true, cancelButtonDisabled: true, isLoading: true });
this.checkIfStatusEnd();
if (this.state.radioArea === true) {
this.hideLayerArea();
var size = /** #type {ol.Size} */ (this.map.getSize());
this.map.getView().setCenter(this.state.center);
this.map.getView().fit(this.state.extent, size);
}
}
downloadImage = () => {
setTimeout( () => {
var canvas = document.getElementsByTagName("canvas")[0];
this.map.once('precompose', (event) => {
this.setDPI(canvas,300);
});
this.map.once('postcompose', (event) => {
var canvas = event.context.canvas;
canvas.toBlob( (blob) => {
this.showLayerArea();
FileSaver.saveAs(blob, "map.png");
this.setState({ imageButtonDisabled: false, cancelButtonDisabled: false, isLoading: false });
// this.props.closePopup();
});
});
}, 400 );
}
setDPI = (canvas, dpi) => {
var scaleFactor = dpi / 96;
canvas.width = Math.ceil(canvas.width * scaleFactor);
canvas.height = Math.ceil(canvas.height * scaleFactor);
var ctx=canvas.getContext("2d");
ctx.scale(scaleFactor, scaleFactor);
}
checkIfStatusEnd = () => {
this.map.getLayers().forEach( (layer) => {
if (layer.getVisible() === true) {
if (layer.values_.name !== 'custom-area') {
this.layersCached.push(layer);
if ((layer.getType() === 'TILE') || (layer.getType() === 'VECTOR_TILE')) {
layer.getSource().on('tileloadstart', () => {
this.addLoading();
});
layer.getSource().on('tileloadend', () => {
this.addLoaded();
});
layer.getSource().on('tileloaderror', () => {
this.addLoaded();
});
} else if (layer.getType() === 'IMAGE') {
layer.getSource().on('imageloadend', () => {
// TO-DO
});
}
}
}
});
}
unsubscribeLayerEvent = () => {
this.layersCached.forEach( (layer) => {
if ((layer.getType() === 'TILE') || (layer.getType() === 'VECTOR_TILE')) {
layer.getSource().un('tileloadend', null);
layer.getSource().un('tileloadend', null);
layer.getSource().un('tileloadend', null);
} else if (layer.getType() === 'IMAGE') {
layer.getSource().un('imageloadend', null);
}
});
}
/* Status Layer */
addLoading = () => {
if (this.loading === 0) {
this.show();
}
++this.loading;
this.update();
}
addLoaded = () => {
var this_ = this;
setTimeout( () => {
++this_.loaded;
this_.update();
}, 100);
}
update = () => {
if (this.loading === this.loaded) {
this.loading = 0;
this.loaded = 0;
var this_ = this;
setTimeout( () => {
this_.hide();
}, 500);
}
}
hide = () => {
if (this.loading === this.loaded) {
console.log('hide');
this.downloadImage();
}
}
show = () => {
console.log('show');
}
Solution
Problem was that a conflict with postcompose method with events added with checkIfStatusEnd to capture if all tiles finished.
handleGetImage = () => {
this.setState({ imageButtonDisabled: true, cancelButtonDisabled: true, isLoading: true });
this.hideLayerArea()
.then( () => {
if (this.state.radioArea === true) {
this.checkIfStatusEnd();
var size = /** #type {ol.Size} */ (this.map.getSize());
this.map.getView().setCenter(this.state.center);
this.map.getView().fit(this.state.extent, size);
this.canvas = document.getElementsByTagName("canvas")[0];
this.map.once('precompose', (event) => {
this.setDPI(this.canvas,300);
});
}
});
}
setDPI = (canvas, dpi) => {
var scaleFactor = dpi / 96;
canvas.width = Math.ceil(canvas.width * scaleFactor);
canvas.height = Math.ceil(canvas.height * scaleFactor);
var ctx=canvas.getContext("2d");
ctx.scale(scaleFactor, scaleFactor);
}
checkIfStatusEnd = () => {
this.map.getLayers().forEach( (layer) => {
if (layer.getVisible() === true) {
if (layer.values_.name !== 'custom-area') {
this.layersCached.push(layer);
if ((layer.getType() === 'TILE') || (layer.getType() === 'VECTOR_TILE')) {
layer.getSource().on('tileloadstart', () => {
this.addLoading();
});
layer.getSource().on('tileloadend', () => {
this.addLoaded();
});
layer.getSource().on('tileloaderror', () => {
this.addLoaded();
});
} else if (layer.getType() === 'IMAGE') {
layer.getSource().on('imageloadstart', () => {
this.addLoading();
});
layer.getSource().on('imageloadend', () => {
this.addLoaded();
});
layer.getSource().on('imageloaderror', () => {
this.addLoaded();
});
}
}
}
});
}
unsubscribeLayerEvent = () => {
this.layersCached.forEach( (layer) => {
if ((layer.getType() === 'TILE') || (layer.getType() === 'VECTOR_TILE')) {
layer.getSource().removeEventListener('tileloadend', null);
layer.getSource().removeEventListener('tileloadend', null);
layer.getSource().removeEventListener('tileloadend', null);
} else if (layer.getType() === 'IMAGE') {
layer.getSource().removeEventListener('imageloadstart', null);
layer.getSource().removeEventListener('imageloadend', null);
layer.getSource().removeEventListener('imageloaderror', null);
}
});
}
/* Status Layer */
addLoading = () => {
++this.loading;
this.update();
}
addLoaded = () => {
setTimeout( () => {
++this.loaded;
this.update();
}, 100);
}
update = () => {
if (this.loading === this.loaded) {
this.loading = 0;
this.loaded = 0;
setTimeout( () => {
this.hide();
}, 500);
}
}
hide = () => {
if (this.loading === this.loaded) {
console.log('finish');
this.downloadImage();
}
}
downloadImage = () => {
var dims = {
a0: [1189, 841],
a1: [841, 594],
a2: [594, 420],
a3: [420, 297],
a4: [297, 210],
a5: [210, 148]
};
var format = this.state.format;
var dim = dims[format];
var imgData = this.canvas.toDataURL("image/jpeg", 1.0);
var pdf;
if (this.state.orientation === 'portrait') {
this.resize(this.canvas, dim[1], dim[0]);
pdf = new jsPDF('portrait', undefined, format);
pdf.addImage(imgData, 'JPEG', 0, 0, dim[1], dim[0]);
} else {
this.resize(this.canvas, dim[1], dim[0]);
pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(imgData, 'JPEG', 0, 0, dim[0], dim[1]);
}
pdf.save(`map-${format}-${this.state.orientation}.pdf`);
this.setState({ imageButtonDisabled: false, cancelButtonDisabled: false, isLoading: false });
this.props.closePopup();
}

Categories

Resources