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());
});
}
});
},
Related
Tried fixing it multiple times and looked over it multiple times but keep on getting the same error: "react-dom.development.js:86 Warning: Received NaN for the children attribute. If this is expected, cast the value to a string."
Need help reviewing this code below and see why that error keeps on showing up
import React, {useState, useEffect} from "react";
function BlackjackGame() {
// useState will return a tuple where the first parameter ()
// ...is the current state of the deck. () allows us to update
// ...the state of the deck.
const [deckFilled, setDeckFilled] = useState(false);
// declaring a new state variable for the card deck
const [cardDeck, setCardDeck] = useState({});
// PLAYER :
// declaring a new state variable for the player
const [gamePlayer, setPlayer] = useState([]);
// declaring a new state variable that holds the player points
const [playerPoints, setPlayerPoints] = useState(0);
// new state variable for optional player points
const [optlPPt, setOptlPPt] = useState(0);
const [showOptlPPt, setShowOptlPPt] = useState(false);
// new state variable for the player cards
const [enablePlayerCards, setEnablePlayerCards] = useState(true);
// new state variable for the when the player is done with their round
const [endOfPlayerRound, setEndOfPlayerRound] = useState(false);
// new state variable for the player buy-in
let playerCurrentBuyIn = 5000;
const [playerBalance, setPlayerBalance] = useState(playerCurrentBuyIn);
// GAME :
// setting the variable for the bet
const[currBet, setBet] = useState(0);
// game round
let round = 3;
const [gameRound, setGameRound] = useState(round);
// game bet
const [placeGameBet, setPlaceGameBet] = useState(true);
// game message
const [msg, setMsg] = useState('How much are you betting?')
const [betButton, setBetButton] = useState(true);
const[forDouble, setForDouble] = useState(false);
const[savedGames, setSavedGames] = useState(false);
const[endOfGame, setEndOfGame] = useState(false);
const[results, setResults] = useState([]);
// DEALER :
// declaring a new state variable for the dealer
const [dealer, setDealer] = useState([]);
// declaring the state variable for that holds the dealer points
const [dealerPoints, setDealerPoints] = useState(0);
// new state variable for optional dealer points
const [optlDlrPt, setOptlDlrPt] = useState(0);
const [showOptlDlrPt, setShowOptlDlrPt] = useState(false);
// back of the dealers card
const [backOfDealersCard, setBackofDealersCard] = useState(false);
// variable for the Hit Button
let hitButton = enablePlayerCards === true && endOfPlayerRound === false && placeGameBet === false;
// variable for the stand button
let standButton = endOfPlayerRound === false && enablePlayerCards === true && placeGameBet === false;
// variable for the double button
let doubleButton = gamePlayer.length === 2 && endOfPlayerRound === false &&
placeGameBet === false && playerBalance >= currBet;
// passing an empty dependencies array to the useEffect hook...
// ...so it runs only when the component mounts
useEffect(() => {
// creating a new deck side effect
composeNewDeck();
window.addEventListener('beforeunload', (event) => {
save()
// cancel the event by the standard
event.preventDefault();
// return the value
return event.returnValue = 'Did you make up your mind?';
})
return() => {
window.removeEventListener('beforeunload', (event) => {
save()
// cancel the event by the standard
event.preventDefault();
// return the value
return event.returnValue = 'Did you make up your mind?';
})
}
}, )
useEffect(() => {
setPlayerPoints(() => {return 0})
setOptlPPt(() => {return 0})
gamePlayer.map((card) => (
card.value === 'Jack' || card.value === 'King' || card.value === 'Queen' ? (
setPlayerPoints((points) => { return points + 10}),
setOptlPPt((points) => { return points + 10})
):
card.value === 'Ace' ? (
setPlayerPoints((points) => { return points + 11}),
setOptlPPt((points) => { return points + 1}),
setShowOptlPPt(() => {return true})
):(
setPlayerPoints((points) => { return points + parseInt(card.value) }),
setOptlPPt((points) => { return points + parseInt(card.value)})
)
))
}, [gamePlayer])
useEffect(() => {
setDealerPoints(() => {return 0})
setOptlDlrPt(() => {return 0})
if (dealer.length === 2 && endOfPlayerRound === false) {
if (dealer[0].value === 'Jack' ||
dealer[0].value === 'King' ||
dealer[0].value === 'Queen' ) {
setDealerPoints((points) => { return points + 10})
setOptlDlrPt((points) => { return points + 10})
} else if (dealer[0].value === 'Ace') {
setDealerPoints((points) => { return points + 11})
setOptlDlrPt((points) => { return points + 1})
setShowOptlDlrPt(() => { return true})
} else {
setDealerPoints((points) => { return points + parseInt(dealer[0].value) })
setOptlDlrPt((points) => { return points + parseInt(dealer[0].value)})
}
} else {
dealer.map((card) => (
card.value === 'Jack' ||
card.value === 'King' ||
card.value === 'Queen' ? (
setDealerPoints((points) => { return points + 10}),
setOptlDlrPt((points) => { return points + 10})
):
card.value === 'Ace' ? (
setDealerPoints((points) => { return points + 11}),
setOptlDlrPt((points) => { return points + 1}),
setShowOptlDlrPt(() => {return true})
): (
setDealerPoints((points) => { return points + parseInt(card.value) }),
setOptlDlrPt((points) => { return points + parseInt(card.value)})
)
))
}
}, [dealer, endOfPlayerRound])
useEffect(() => {
if (playerPoints > 21 && optlPPt > 21) {
setEnablePlayerCards(() => {return false})
setMsg('Uh Oh...Looks like you lost');
setTimeout(() => {
dealerWon();
}, 2000);
} else if (playerPoints === 21 || optlPPt === 21) {
setMsg("Now you see...Blackjack!")
setEnablePlayerCards(() => {return false})
setTimeout(() => {
stand()
}, 2000);
} else {
forDouble === true && stand();
}
}, [playerPoints])
useEffect(() => {
if ( ((endOfPlayerRound === true && dealerPoints <= 16) ||
(dealerPoints > 21 && optlDlrPt <= 16)) && dealerPoints !== 0) {
setMsg("Computers turn");
draw(false, drawFirstCard);
} else if (endOfPlayerRound === true && dealerPoints !== 0) {
let comparePlayersPoint;
let compareDealerPoint;
if (playerPoints > 21 && (optlPPt > 0 && optlPPt <= 21) ) {
comparePlayersPoint = optlPPt;
} else {
comparePlayersPoint = playerPoints;
}
if( dealerPoints > 21 && optlDlrPt > 21){
compareDealerPoint = 0;
} else if (dealerPoints > 21 && (optlDlrPt > 0 && optlDlrPt <= 21)) {
compareDealerPoint = optlDlrPt;
} else if (dealerPoints <= 21) {
compareDealerPoint = dealerPoints;
}
if( (21 - comparePlayersPoint) < (21 - compareDealerPoint) ) {
setMsg("You won")
setTimeout(() => {
playerWon();
}, 2000);
} else if ((21 - comparePlayersPoint) > (21 - compareDealerPoint)){
setMsg("Computer won")
setTimeout(() => {
dealerWon();
}, 2000);
} else {
setMsg("Draw")
setTimeout(() => {
noWinner();
}, 2000);
}
}
}, [dealerPoints])
useEffect(() => {
if (placeGameBet === true) {
setMsg("How much are you betting?");
setBetButton(true);
}
}, [placeGameBet])
useEffect(() => {
if ( gameRound > 5 ) {
endGame();
} else if (gameRound !== 1 && savedGames === false) {
nextRound();
} else {
setSavedGames(false);
}
}, [gameRound])
// calling the Deck Of Cards API to fecth the cards
const composeNewDeck = () => {
fetch(deckOfCardsLink + shuffleDeckOfCards + deckAmt, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
setDeckFilled(() => { return true; })
setCardDeck( () => { return {...responseData}; })
})
.catch(err => {
console.log('error : ' + err);
});
}
// calling the Deck Of Cards API to draw a card
const draw = (forPlayers, amtOfCards) => {
fetch(deckOfCardsLink + cardDeck.deck_id + amtOfCards, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
if (forPlayers === true) {
setPlayer((playerHand) => { return [...playerHand, ...responseData.cards]; })
} else {
setDealer((dealerHand) => { return [...dealerHand, ...responseData.cards]; })
}
})
.catch(err => {
console.log('error : ' + err);
});
}
// calling the Deck Of Cards API to shuffle the card deck
const shuffleDeck = (deckId) => {
fetch(deckOfCardsLink + deckId + reShuffleDeckOfCard, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
setDeckFilled(() => { return true; })
setCardDeck( () => { return {...responseData}; })
})
.catch(err => {
console.log('error : ' + err);
});
}
const stand = () => {
setBackofDealersCard(() => {return true})
setTimeout(() => {
setEndOfPlayerRound(() => {return true})
setEnablePlayerCards(() => {return false})
}, 250);
}
const double = () => {
setForDouble(true);
setMsg("Going for double!")
setPlayerBalance((balance) => {return balance - currBet})
setBet((bet) => {return bet+bet})
draw(true, drawFirstCard);
}
const startRound = () => {
setEndOfPlayerRound(false);
setEnablePlayerCards(true);
setPlaceGameBet(false);
setBetButton(false);
setMsg("Your turn");
if (deckFilled === true) {
draw(true, drawSecondCard);
draw(false, drawSecondCard);
}
}
const bet = (amount) => {
if (playerBalance - amount >= 0) {
setPlayerBalance((balance) => { return balance - amount});
setBet((bet) => {return bet + amount})
}
}
const playerWon = () => {
setPlayerBalance((balance) => {return balance + (currBet * 1.5)})
setGameRound((round) => {return round + 1});
}
const dealerWon = () => {
setGameRound((round) => {return round + 1});
}
const noWinner = () => {
setPlayerBalance((balance) => {return balance + currBet})
setGameRound((round) => {return round + 1});
}
const nextRound = () => {
setBackofDealersCard(false);
setForDouble(false);
setShowOptlDlrPt(false);
setShowOptlPPt(false);
setPlayerPoints(0);
setOptlPPt(0);
setDealerPoints(0);
setOptlDlrPt(0);
setPlaceGameBet(true);
setBetButton(true);
setBet(0);
setPlayer([]);
setDealer([]);
}
const endGame = () => {
setEndOfGame(true);
setBet(0);
setMsg("Game Over");
let rank = JSON.parse(localStorage.getItem("rank"));
if( rank === undefined || rank === null) {
localStorage.setItem("rank", JSON.stringify({
points: [playerBalance]
}))
} else {
let sortedRank = rank.points.sort(function(a, b) {
return b - a;
})
if (sortedRank.length<=2) {
setResults([...sortedRank])
} else {
setResults([sortedRank[0],sortedRank[1],sortedRank[2]])
}
localStorage.setItem("rank", JSON.stringify({
points: [...rank.points, playerBalance]
}))
}
}
const reset = () => {
setEndOfGame(false);
setDeckFilled(false);
shuffleDeck(cardDeck.deck_id);
nextRound();
setGameRound(3);
setPlayerBalance(5000);
}
const save = () => {
localStorage.setItem("savedGame", JSON.stringify(
{
deckFilled: deckFilled,
cardDeck: cardDeck,
gamePlayer: gamePlayer,
dealer: dealer,
playerPoints: playerPoints,
dealerPoints: dealerPoints,
optlPPt: optlPPt,
showOptlPPt: showOptlPPt,
optlDlrPt: optlDlrPt,
showOptlDlrPt: showOptlDlrPt,
enablePlayerCards: enablePlayerCards,
endOfPlayerRound: endOfPlayerRound,
playerBalance: playerBalance,
currBet: currBet,
backOfDealersCard: backOfDealersCard,
gameRound: gameRound,
placeGameBet: placeGameBet,
msg: msg,
betButton: betButton,
forDouble: forDouble,
}
));
}
const load = () => {
setSavedGames(true);
let gameSave = JSON.parse(localStorage.getItem('savedGame'));
if (gameSave !== undefined) {
setCardDeck(gameSave.cardDeck);
setPlayer(gameSave.gamePlayer);
setDealer(gameSave.dealer);
setPlayerPoints(gameSave.playerPoints);
setDealerPoints(gameSave.dealerPoints);
setOptlPPt(gameSave.optlPPt);
setShowOptlPPt(gameSave.showOptlPPt);
setOptlDlrPt(gameSave.optlDlrPt);
setShowOptlDlrPt(gameSave.showOptlDlrPt);
setEnablePlayerCards(gameSave.enablePlayerCards);
setEndOfPlayerRound(gameSave.endOfPlayerRound);
setPlayerBalance(gameSave.playerBalance);
setBet(gameSave.currBet);
setBackofDealersCard(gameSave.backOfDealersCard);
setGameRound(gameSave.gameRound);
setPlaceGameBet(gameSave.placeGameBet);
setMsg(gameSave.msg);
setBetButton(gameSave.betButton);
setForDouble(gameSave.forDouble);
setDeckFilled(gameSave.deckFilled);
}
}
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');
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?
FilterCriterias: any = []
public productChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'productType') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if (elem.filterValueList?.length == 0 && elem.filtercolumnName == 'productType') {
// const idy = elem.filtercolumnName.indexOf('productType')
// if (idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'productType') {
console.log(true);
const idy = element.filtercolumnName.indexOf('productType')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
public collectionChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'collections') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if(elem.filterValueList?.length == 0) {
// const idy = elem.filtercolumnName.indexOf('collections')
// console.log('collectoinindex',idy);
// if(idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'collections') {
console.log(true);
const idy = element.filtercolumnName.indexOf('collections')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
I am having two functions in which I want to generate a format like below
FilterCriterias: [
{
filtercolumnName:`producttype`,
filterValueList: [`hat`, 'cup']
},
{
filtercolumnName: "collections",
filterValueList: [`modern`, 'pant']
},
]
if the filterValueList.length == 0 means i want to remove the entire object which hold the filerValueList.length == 0.
For Example, if filterValueList of collections is empty means only the producttype needs to be there in the array.
You can achieve that using Array.filter function, like the following:
this.FilterCriterias = this.FilterCriterias.filter(
(item) => !!item.filterValueList.length
);
I am guessing this should do the job if I understood correctly what you want to do. This will loop through all objects of the array, check if their filterValueList array is empty and if so, it will remove them from the array:
let i = 0;
while (i < FilterCriterias.length) {
if(FilterCriterias[i].filterValueList.length == 0) {
FilterCriterias.splice(i, 1);
} else {
i++;
}
}
I'm trying to remove nodes, type layer, but I'm going crazy... AGHHH!!
I'm using a tree. Using a component of react (rc-tree). There are two types of items: folders and layers.
And I want when delete a folder remove all items inside and when an item will be a layer, different a folder, I could call other method to remove layer from map.
parentis a property that I add when I drop inside a layer on folder.
This is an example of my tree:
And here is my code:
removeNodes = (desiredNode) => {
var parent;
if (desiredNode.parent === undefined && desiredNode.children) {
console.log('1');
} else if (desiredNode.parent !== undefined && desiredNode.children) {
console.log('2', desiredNode);
}
else if (desiredNode.parent !== undefined && !desiredNode.children) {
console.log('3');
parent = getNodeByKey(desiredNode.parent, this.treeData);
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(desiredNode.key) === 0) {
if (parent.children[index].type.localeCompare('folder') !== 0) {
console.log('remove layer with keyName: ', parent.children[index].keyName);
}
parent.children.splice(index, 1);
this.removeTrashCheckedKeys();
}
});
delete parent.children;
}
else {
console.log('4')
var pos = this.treeData.indexOf(desiredNode);
if (this.treeData[pos].type.localeCompare('folder') !== 0) {
console.log('remove layer with keyName: ', this.treeData[pos].keyName);
}
this.treeData.splice(pos, 1);
this.removeTrashCheckedKeys();
}
}
EDIT: This is an idea of a better implementation, but now I have to manage when tree has children, I have to find layers to call a method removeLayerWithName(tree.keyName); to remove layer added in map.
removeNodes = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
this.removeNodes(node);
});
} else {
var parent = getNodeByKey(tree.parent, this.treeData);
if (parent.children) {
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(tree.key) === 0) {
if (tree.type.localeCompare('folder') !== 0) {
// this.removeLayerWithName(tree.keyName);
console.log('remove layer with keyName: ', tree.keyName)
}
parent.children.splice(index,1);
}
});
if (parent.children.length === 0) {
delete parent.children;
}
} else {
var pos = this.treeData.indexOf(tree);
if (tree.type.localeCompare('folder') !== 0) {
// this.removeLayerWithName(tree.keyName);
console.log('remove layer with keyName: ', tree.keyName);
}
this.treeData.splice(pos, 1);
}
}
this.removeTrashCheckedKeys();
}
I'm making a wild guess here, but does delete parent.children; completely wipe your collection, thus any bindings to it start failing?
You modify that collection, then delete it, seems weird.
SOLUTION:
onDelete = (event, key) => {
if (!window.confirm('Do you want remove it?')) {
return;
} else {
var node = getNodeByKey(key, this.treeData);
this.removeNodes(node);
this.setState({ treeData: this.treeData }, () => {
var parent = getNodeByKey(node.parent, this.treeData);
delete parent.children;
this.props.parentTree(this.treeData);
});
}
this.orderFiles();
event.stopPropagation();
};
removeNodes = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
if (!node.children) {
if (node.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(node);
var parent = getNodeByKey(node.parent, this.treeData);
parent.children.splice(index,1);
if (parent.children.length > 0) {
this.removeNodes(parent);
}
}
} else {
this.removeNodes(node);
}
});
} else {
var parent = getNodeByKey(tree.parent, this.treeData);
if (parent.children) {
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(tree.key) === 0) {
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
parent.children.splice(index,1);
}
});
if (parent.children.length === 0) {
delete parent.children;
}
} else {
var pos = this.treeData.indexOf(tree);
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
this.treeData.splice(pos, 1);
}
}
this.removeTrashCheckedKeys();
}
A better implementation:
onDelete = (event, key) => {
if (!window.confirm('¿Estás seguro de eliminarlo?')) {
return;
} else {
var node = getNodeByKey(key, this.treeData);
this.removeNodes(node);
this.setState({ treeData: this.treeData }, () => {
this.props.parentTree(this.treeData);
});
}
this.orderFiles();
event.stopPropagation();
};
removeNodes = (tree) => {
this.layersInTree = [];
this.findLayersInTree(tree);
if (!tree.parent) {
delete tree.children;
var pos = this.treeData.indexOf(tree);
this.treeData.splice(pos, 1);
} else {
var parentNode = getNodeByKey(tree.parent, this.treeData);
delete parentNode.children;
}
}
findLayersInTree = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
if (!node.children && node.type.localeCompare('folder') !== 0 ) {
this.removeLayerWithName(node);
} else {
this.findLayersInTree(node);
}
});
} else {
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
}
}
removeLayerWithName = (nodeLayer) => {
var nodeLayerKeyName = String(nodeLayer.keyName);
this.map.getLayers().forEach( (layer) => {
if (layer !== undefined) {
var layerKeyName = String(layer.getProperties().keyName);
if (layerKeyName.localeCompare(nodeLayerKeyName) === 0) {
this.map.removeLayer(layer);
}
}
});
}