Cant access method to download Image - javascript

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();
}

Related

Chrome extension: stop script on multiple tabs once element is clicked

there are two pages that shows a button at random intervals. So I have this code to continously search for the button page element and click it quickly once it appears.
However the script needs to pause on all tabs once the element is found and clicked in one of the tabs. How can I modify this to stop the script on all tabs running it once the element is found in one of the tabs?
function stopSeekAndClick() {
chrome.storage.sync.get("interval", ({ interval }) => {
chrome.storage.sync.set({ interval: null });
clearInterval(interval);
});
}
document.addEventListener("DOMContentLoaded", function () {
const form = document.getElementById("autoclicker-ext-form");
const textInput = document.getElementById("autoclicker-ext-search-text");
const tagInput = document.getElementById("autoclicker-ext-search-tag");
const searchIdInput = document.getElementById("autoclicker-ext-search-id");
const iframeIdInput = document.getElementById("autoclicker-ext-iframe-id");
const customAttribInput = document.getElementById("autoclicker-ext-custom-attrib");
const submitButton = document.getElementById("autoclicker-ext-enable");
const stopButton = document.getElementById("autoclicker-ext-disable");
chrome.storage.sync.get("interval", ({ interval }) => {
if (!!interval) {
submitButton.value = "Running search...";
submitButton.disabled = true;
stopButton.disabled = false;
} else {
submitButton.value = "Start seek & click";
stopButton.disabled = true;
submitButton.disabled = false;
}
});
chrome.storage.sync.get("data", ({ data }) => {
if (!data) return;
const { tag, search, searchId, iframeId, customAttrib } = data;
tagInput.value = tag || "";
textInput.value = search || "";
searchIdInput.value = searchId || "";
iframeIdInput.value = iframeId || "";
customAttribInput.value = customAttrib || "";
});
form.addEventListener("submit", async function (e) {
e.preventDefault();
if (e.submitter.id === "autoclicker-ext-disable") {
submitButton.value = "Start seek & click";
stopButton.disabled = true;
submitButton.disabled = false;
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true, });
await chrome.scripting.executeScript({ target: { tabId: tab.id }, function: stopSeekAndClick, });
return;
}
submitButton.value = "Running search...";
submitButton.disabled = true;
stopButton.disabled = false;
chrome.storage.sync.set({
data: {
search: form.elements.search.value,
tag: form.elements.tag.value,
searchId: form.elements.searchId.value,
delay: Number(form.elements.delay.value) * 1,
iframeId: form.elements.iframeId.value,
customAttrib: form.elements.customAttrib.value,
}, });
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.scripting.executeScript({ target: { tabId: tab.id }, function: startSeekAndClick, });
});
});
function startSeekAndClick() {
function getElementsByText(document, str, tag = "button") {
return new Array(...document.getElementsByTagName(tag))
.filter((el) => !!el && String(el.innerText).startsWith(str));
}
chrome.storage.sync.get("data", ({ data }) => {
if (!data) return;
function notFound() {
clearInterval(interval);
}
const interval = setInterval(() => {
let element;
let selectedDocument = document;
if (!!data.iframeId) {
selectedDocument = document
? document.getElementById(data.iframeId)?.contentWindow?.document
: null;
if (!selectedDocument) {
notFound();
return;
}
}
element =
data.searchId !== ""
? selectedDocument.getElementById(data.searchId)
: getElementsByText(selectedDocument, data.search, data.tag)[0];
if (element) {
if (!!data.customAttrib) {
const [attribKey, attribValue] = data.customAttrib.replaceAll('"', "").split("=");
if (element.hasAttribute(attribKey) && element.getAttribute(attribKey) === attribValue) {
element.click();
}
} else {
element.click();
}
chrome.storage.sync.get("element", ({ oldElement }) => {
if (element !== oldElement) {
chrome.storage.sync.set({ interval, element });
}
});
}
}, data.delay || 1);
});
}

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 to get activate particular conversation chat

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?

apis delcared in contextbridge undefined in render process

I've been working on updating a electron app from 11.x to 12.x and have run into an issue where the apis declared by contextBridge.exposeInMainWorld come as undefined when called upon through window.
This is my preload.js file
const { contextBridge, ipcRenderer } = require('electron');
const { path } = require('path')
contextBridge.exposeInMainWorld('api',{
getPath: (filePath) => {
return path.parse(filePath).base;
},
removeAllListeners: (ListenerType) => {
ipcRenderer.removeAllListeners(ListenerType);
},
openNewPDF: (pdf) => {
ipcRenderer.send('openNewPDF',pdf);
},
newWindow: (file) => {
ipcRenderer.send('newWindow',file);
},
togglePrinting: (value) => {
ipcRenderer.send('togglePrinting',value)
},
resizeWindow: (value) => {
ipcRenderer.send('resizeWindow', value)
}
});
my app.js
function createWindow(filename = null) {
// Create the browser window.
let win = new BrowserWindow({
width: 550,
height: 420,
minWidth: 565,
minHeight: 200,
preload: path.resolve(path.join(__dirname, 'app/preload.js')),
resizable: true,
titleBarStyle: 'default',
show: false
});
wins.push(win);
// and load the index.html of the app.
win.loadFile('app/index.html');
win.openDevTools();
let wc = win.webContents
wc.on('will-navigate', function (e, url) {
if (url != wc.getURL()) {
e.preventDefault()
shell.openExternal(url)
}
})
win.once('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
wins = [];
});
win.webContents.removeAllListeners('did-finish-load');
win.webContents.once('did-finish-load', () => {
if (filename) {
win.webContents.send('file-open', filename);
win.show();
} else {
win.show();
}
});
if (!menuIsConfigured) {
const menu = Menu.buildFromTemplate(menuTemplate);
menu.getMenuItemById('file-open').click = () => {
openNewPDF();
};
menu.getMenuItemById('file-print').click = () => {
const focusedWin = BrowserWindow.getFocusedWindow();
focusedWin.webContents.send('file-print');
};
Menu.setApplicationMenu(menu);
menuIsConfigured = true;
}
const openNewPDF = () => {
dialog
.showOpenDialog(null, {
properties: ['openFile'],
filters: [{ name: 'PDF Files', extensions: ['pdf'] }]
})
.then((dialogReturn) => {
const filename = dialogReturn['filePaths'][0];
if (filename) {
if (wins.length === 0) {
createWindow(filename.toString());
} else {
const focusedWin = BrowserWindow.getFocusedWindow();
if (focusedWin) {
focusedWin.webContents.send('file-open', filename.toString());
}
}
}
});
}
ipcMain.removeAllListeners('togglePrinting');
ipcMain.once('togglePrinting', (e, msg) => {
const menu = Menu.getApplicationMenu();
menu.getMenuItemById('file-print').enabled = Boolean(msg);
});
ipcMain.removeAllListeners('newWindow');
ipcMain.once('newWindow', (e, msg) => {
console.log('opening ', msg, ' in new window');
createWindow(msg);
});
ipcMain.removeAllListeners('resizeWindow');
ipcMain.once('resizeWindow', (e, msg) => {
const { width, height } = win.getBounds();
if (width < 1000 || height < 650) {
win.setResizable(true);
win.setSize(1000, 650);
win.center();
}
});
ipcMain.removeAllListeners('openNewPDF');
ipcMain.once('openNewPDF', (e, msg) => {
openNewPDF();
});
}
let fileToOpen = '';
const args = process.argv;
const argsLength = args.length;
if (argsLength > 1 && args[argsLength - 1].endsWith('.pdf')) {
fileToOpen = args[argsLength - 1];
}
app.on('open-file', (event, path) => {
event.preventDefault();
if (app.isReady()) {
if (wins.length === 0) {
createWindow(path.toString());
} else {
const focusedWin = BrowserWindow.getFocusedWindow();
focusedWin.webContents.send('file-open', path.toString());
}
}
fileToOpen = path.toString();
});
app.whenReady().then(() => {
if (fileToOpen) {
createWindow(fileToOpen);
} else {
createWindow();
}
});
app.on('window-all-closed', () => {
app.quit()
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
I'm lost on why contextBridge doesn't work.
The object passed to the BrowserWindow constructor is not correct. The preload option should be a property of webPreferences
const win = new BrowserWindow({
webPreferences: {
preload: YOUR_PRELOAD_SCRIPT_PATH
}
});
See the docs

drag and drop not work in cypress but working by user

#craftjs/core was used in my project.
when user drag and drop tools for add to canvas everything works fine ( component created in canvas)
but in cypress after drop not happening ( component not created in canvas).
in ToolBox componnet:
...
const { connectors } = useEditor();
const dragStart = (e) => {
e.dataTransfer.setData('text/html', e.parentNode);
setExpanded(false);
};
...
<Accordion expanded={expanded} onChange={() => setExpanded(!expanded)}>
<AccordionSummary
expandIcon={<i className="fal fa-chevron-down" />}
aria-controls="toolbox-content"
id="ToolBoxPanel"
>
<small>ToolBox</small>
</AccordionSummary>
<AccordionDetails className="justify-content-center p-0">
<MaterialButton
aria-label="text"
onDragStart={dragStart}
variant="text"
color="secondary"
className="my-1 p-1 toolsButton mx-1"
>
<i
className="fal fa-font "
ref={(ref) => {
connectors.create(ref, <Text text="Type anything" />);
}}
/>
</MaterialButton>
.
.
.
in cypress/integration/spec.js
describe("Drag and Drop", () => {
beforeEach(() => {
cy.visit('/');
cy.waitForReact();
})
it('should add text componnent to canvas', () => {
cy.contains('ToolBox').click().wait(500)
cy.get('#body').then($editor=>{
cy.get('.toolsButton[aria-label="text"] i').realHover().trigger('mousedown').reactDnd($editor,{offsetX:300,offsetX:300});
cy.wait(5000);
})
})
});
in cypress/support/commands.js
Cypress.Commands.add('reactDnd', {
prevSubject: 'element',
}, (sourceSelector, targetSelector, options) => {
const dataTransfer = new DataTransfer;
const opts = {
offsetX: 100,
offsetY: 100,
...(options || {})
};
cy.wrap(sourceSelector.get(0))
.trigger('dragstart', {
dataTransfer,
}).wait(1000);
cy.get(targetSelector).then($el => {
const {
x,
y,
} = $el.get(0).getBoundingClientRect();
cy.wrap($el.get(0)).realHover()
.trigger('dragover', {
dataTransfer,
}).wait(1000).trigger('mouseover').wait(1000)
.trigger('drop', {
dataTransfer,
clientX: x + opts.offsetX,
clientY: y + opts.offsetY,
}).trigger('dragend', {
dataTransfer,
}).trigger('mouseup');
})
});
class DndSimulatorDataTransfer {
constructor(){
this.data = {};
this.dropEffect = 'move';
this.effectAllowed = 'all';
this.files = [];
this.items = [];
this.types = [];
}
clearData(format) {
if (format) {
delete this.data[format]
const index = this.types.indexOf(format)
delete this.types[index]
delete this.data[index]
} else {
this.data = {}
}
}
setData(format, data) {
this.data[format] = data
this.items.push(data)
this.types.push(format)
}
getData(format) {
if (format in this.data) {
return this.data[format]
}
return ''
}
setDragImage(img, xOffset, yOffset) {}
}
Cypress.Commands.add('reactDnd', {
prevSubject: 'element',
}, (sourceSelector, targetSelector, options) => {
const dataTransfer = new DndSimulatorDataTransfer();
const opts = {
offsetX: 100,
offsetY: 100,
...(options || {})
};
cy.wrap(sourceSelector.get(0))
.trigger('dragstart', {
dataTransfer,
})
.trigger('pointercancel', {
dataTransfer,
force:true,
})
.trigger('drag', {
force:true,
dataTransfer,
})
.trigger('dragenter', {
force:true,
dataTransfer,
})
.wait(100);
cy.get(targetSelector).then($el => {
const {
x,
y,
} = $el.get(0).getBoundingClientRect();
cy.wrap($el.get(0))
.trigger('dragenter', {
dataTransfer,
})
.trigger('drag', {
dataTransfer,
})
.trigger('dragover', {
dataTransfer,
})
.trigger('drop', {
dataTransfer,
clientX: x + opts.offsetX,
clientY: y + opts.offsetY,
force: true
})
.wait(1000);
cy.wrap(sourceSelector.get(0)).trigger('dragend', {
dataTransfer,
force: true
});
})
});

Categories

Resources