element.remove() and element.append() conflicting with each other - append

I am writing a chess game in JavaScript/React.
When I drag the white piece to the black piece, I am trying to remove the black piece and append the white one, like this :
function drop(ev) {
ev.preventDefault();
//Set the background to original color on droping the piece:
ev.target.style.backgroundColor = ev.target.dataset.squarecolor
//Save moving piece data into an object:
let movingPiece = JSON.parse(ev.dataTransfer.getData("Text"))
if (movingPiece.color === 'white' && ev.target?.dataset?.color === 'black' && ev.target.nodeName === 'IMG')
{
ev.target.remove()
ev.target.append(document.getElementById(movingPiece.id));
}
}
So:
Remove black piece
Add white piece
But I end up with 0 pieces on the screen. Not sure if this is because of render or JS is removing the newly appended item.
Reproducible example:
https://codesandbox.io/s/chess-app-11qvk9?file=/src/components/pieces.jsx

No need to remove
function drop(ev) {
ev.preventDefault();
//Set the background to original color on droping the piece:
ev.target.style.backgroundColor = ev.target.dataset.squarecolor
//Save moving piece data into an object:
let movingPiece = JSON.parse(ev.dataTransfer.getData("Text"))
if (movingPiece.color === 'white')
{
//ev.target.remove()
ev.target.append(document.getElementById(movingPiece.id));
}
}

Related

Need to set border around PDAnnotationTextMarkup, Highlight text in PDF

Desired Result:
How do I set border(red) to my PDAnnotationTextMarkup? Just need to work with AdobePDF mainly.
def addCoordinates(cord: List[Coordinates], page) : PDPage = {
val annotations = page.getAnnotations
val borderThick = new PDBorderStyleDictionary()
borderThick.setWidth(0.8.toFloat)
borderThick.setStyle(PDBorderStyleDictionary.STYLE_SOLID)
cord.foreach {
val textM = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT)
textM.setBorderStyle(borderThick)
textM.setColor(yellow)
// Set rectange and quads
annotations.add(markup) // Need to set border to markup?
// Below code i was able to get red border with Square annotation.
// This is more kind of workaround, see two annotations in Adobe PDF (not user friendly.)
val aSquare = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_SQUARE)
aSquare.setColor(red);
// set rectange and quads
annotations.add(aSquare)
}
page
}

leaftletjs-adding points dynamically and draw line string

I am trying to draw the path of a flight using leafletjs and geojson. I'll be getting the geometry from a stream.
this is what I have done so far:
let index = 0;
let geoJsonLayer;
let intervalFn = setInterval(function () {
let point = trackData.features[index++];
if(point) {
let coords = point.geometry.coordinates;
coords.pop();
coords.reverse();
geoFeature.geometry.coordinates.push(coords);
if(map.hasLayer(geoJsonLayer)) map.removeLayer(geoJsonLayer);
geoJsonLayer = L.geoJson(geoFeature, {
onEachFeature: (feature, layer) => {
const content = feature.properties.title;
layer.bindPopup(content);
}
});
geoJsonLayer.addTo(map);
// console.log(coords);
} else {
clearInterval(intervalFn);
}
}, 100);
setInterval is to simulate the part whereby I get the geometry from a stream.
now when a user clicks on the path I need to show some properties of the path, and I am trying to use the onEachFeature for that, but its not working correctly.
I suspect its because I am removing the layers (I did this to improve the performance)
Is there any other better ways to do what I am trying to achieve ?
You should probably try addLatLng()
Adds a given point to the polyline.
Your geoFeature sounds to be a single Feature, so your geoJsonLayer will contain a single layer (polyline):
let myPolyline;
geoJsonLayer.eachLayer(function (layer) {
myPolyline = layer; // Will be done only once actually.
});
// When you receive a new point…
myPolyline.addLatLng([lat, lng]);
With this you should not have to remove your layers every time.
The popup should therefore stay open, if it is shown.
Demo: https://jsfiddle.net/3v7hd2vx/265/ (click on the button to add new points)

Display values outside of pie chart in chartjs

When I hover on pie chart, the values are displayed in tooltip. However, I want to display values outside of pie chart. I want to make chart like this image:
How to do this?
I was able to get something similar working using chart.js v2.3.0 using both the plugin API and extending chart types API. You should be able to take this as a starting point and tweak it to your needs.
Here is how it looks after being rendered.
Note, this requires digging deep into chart.js internals and could break if they change the way tooltips are positioned or rendered in the future. I also added a new configuration option called showAllTooltips to enable selectively using the plugin on certain charts. This should work for all chart types, but I am currently only using it for pie, doughnut, bar, and line charts so far.
With that said, here is a working solution for the image above.
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create a namespace to persist plugin state (which unfortunately we have to do)
if (!chart.showAllTooltipsPlugin) {
chart.showAllTooltipsPlugin = {};
}
// turn off normal tooltips in case it was also enabled (which is the global default)
chart.options.tooltips.enabled = false;
// we can't use the chart tooltip because there is only one tooltip per chart which gets
// re-positioned via animation steps.....so let's create a place to hold our tooltips
chart.showAllTooltipsPlugin.tooltipsCollection = [];
// create a tooltip for each plot on the chart
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
// but only create one for pie and doughnut charts if the plot is large enough to even see
if (!_.contains(['doughnut', 'pie'], sector._chart.config.type) || sector._model.circumference > 0.1) {
var tooltip;
// create a new tooltip based upon configuration
if (chart.config.options.showAllTooltips.extendOut) {
// this tooltip reverses the location of the carets from the default
tooltip = new Chart.TooltipReversed({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart);
} else {
tooltip = new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart);
}
// might as well initialize this now...it would be a waste to do it once we are looping over our tooltips
tooltip.initialize();
// save the tooltips so they can be rendered later
chart.showAllTooltipsPlugin.tooltipsCollection.push(tooltip);
}
});
});
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we want to wait until everything on the chart has been rendered before showing the
// tooltips for the first time...otherwise it looks weird
if (!chart.showAllTooltipsPlugin.initialRenderComplete) {
// still animating until easing === 1
if (easing !== 1) {
return;
}
// animation is complete, let's remember that fact
chart.showAllTooltipsPlugin.initialRenderComplete = true;
}
// at this point the chart has been fully rendered for the first time so start rendering tooltips
Chart.helpers.each(chart.showAllTooltipsPlugin.tooltipsCollection, function (tooltip) {
// create a namespace to persist plugin state within this tooltip (which unfortunately we have to do)
if (!tooltip.showAllTooltipsPlugin) {
tooltip.showAllTooltipsPlugin = {};
}
// re-enable this tooltip otherise it won't be drawn (remember we disabled all tooltips in beforeRender)
tooltip._options.enabled = true;
// perform standard tooltip setup (which determines it's alignment and x, y coordinates)
tooltip.update(); // determines alignment/position and stores in _view
tooltip.pivot(); // we don't actually need this since we are not animating tooltips, but let's be consistent
tooltip.transition(easing).draw(); // render and animate the tooltip
// disable this tooltip in case something else tries to do something with it later
tooltip._options.enabled = false;
});
}
},
});
// A 'reversed' tooltip places the caret on the opposite side from the current default.
// In order to do this we just need to change the 'alignment' logic
Chart.TooltipReversed = Chart.Tooltip.extend({
// Note: tooltipSize is the size of the box (not including the caret)
determineAlignment: function(tooltipSize) {
var me = this;
var model = me._model;
var chart = me._chart;
var chartArea = me._chartInstance.chartArea;
// set caret position to top or bottom if tooltip y position will extend outsite the chart top/bottom
if (model.y < tooltipSize.height) {
model.yAlign = 'top';
} else if (model.y > (chart.height - tooltipSize.height)) {
model.yAlign = 'bottom';
}
var leftAlign, rightAlign; // functions to determine left, right alignment
var overflowLeft, overflowRight; // functions to determine if left/right alignment causes tooltip to go outside chart
var yAlign; // function to get the y alignment if the tooltip goes outside of the left or right edges
var midX = (chartArea.left + chartArea.right) / 2;
var midY = (chartArea.top + chartArea.bottom) / 2;
if (model.yAlign === 'center') {
leftAlign = function(x) {
return x >= midX;
};
rightAlign = function(x) {
return x < midX;
};
} else {
leftAlign = function(x) {
return x <= (tooltipSize.width / 2);
};
rightAlign = function(x) {
return x >= (chart.width - (tooltipSize.width / 2));
};
}
overflowLeft = function(x) {
return x - tooltipSize.width < 0;
};
overflowRight = function(x) {
return x + tooltipSize.width > chart.width;
};
yAlign = function(y) {
return y <= midY ? 'bottom' : 'top';
};
if (leftAlign(model.x)) {
model.xAlign = 'left';
// Is tooltip too wide and goes over the right side of the chart.?
if (overflowLeft(model.x)) {
model.xAlign = 'center';
model.yAlign = yAlign(model.y);
}
} else if (rightAlign(model.x)) {
model.xAlign = 'right';
// Is tooltip too wide and goes outside left edge of canvas?
if (overflowRight(model.x)) {
model.xAlign = 'center';
model.yAlign = yAlign(model.y);
}
}
}
});

Leaflet several featuregroups order changes when toggled

I am using Leaflet.js to create a map. The data displayed on the map depends on user selection so I instantiate two empty feature groups on map load, one for the values, and one for a color marker behind the value ( color depends on the value ).
if( dHMT.dataColorLayer===undefined ){
dHMT.dataColorLayer = new L.featureGroup({}).addTo(dHMT.map);
}
if( dHMT.dataValueLayer===undefined ){
dHMT.dataValueLayer = new L.featureGroup({}).addTo(dHMT.map);
}
I then add the empty layers to the layer switcher.
dHMT.overlayMapsLS = {
"Bassins ": dHMT.bassinLayer,
"Couleurs ": dHMT.dataColorLayer,
"Données ": dHMT.dataValueLayer
};
Once the user selects data, the featureGroups are filled with the relevant values/markers.
var iconColor = L.divIcon({className: 'dataSpans',html:"<div style='text-align: center;border-radius: 50%;height:40px;width:40px;padding-top:9px;background:"+dHMT.siteinfo[x].color+"'></div>"});
var iconColorDiv = L.marker([dHMT.ecartArray[x].lat, dHMT.ecartArray[x].lon], {icon: iconColor})
.bindPopup(
'Nom : '+dHMT.siteinfo[x].name+'<br>'+
'Numéro : '+dHMT.siteinfo[x].stnm+'<br>'+
'Stid : '+dHMT.siteinfo[x].stid+'<br>'+
'LatLon : '+dHMT.siteinfo[x].lat+','+dHMT.ecartArray[x].lon+'<br>'+
'Valeur : '+dHMT.ecartArray[x].ecart+'<br>'
).on('mouseover', function (e) {
this.openPopup();
}).on('mouseout', function (e) {
this.closePopup();
});
var iconValue = L.divIcon({className: 'dataSpans',html:"<div style='text-align: center;height:40px;width:40px;padding-top:9px;'>"+value+"</div>"});
var iconValueDiv = L.marker([dHMT.ecartArray[x].lat, dHMT.ecartArray[x].lon], {icon: iconValue});
dataColorFeatures.push(iconColorDiv);
dataValueFeatures.push(iconValueDiv);
L.featureGroup(dataColorFeatures).addTo(dHMT.dataColorLayer);
L.featureGroup(dataValueFeatures).addTo(dHMT.dataValueLayer);
Both layers are fine, I have a nice map with a marker layer with colored circles with another layer displaying values over the marker. The goal being to deactivate the colors or the values using the layer switcher.
The problem is that if, for example, I toggle the color layer off, and turn it on again, the colored circles reappear over the values. The desired behavior would be to have them reappear in the original order, behind the values.
You can listen to the overlayadd event on your L.Map instance:
Fired when an overlay is selected through the layer control.
http://leafletjs.com/reference.html#map-overlayadd
When fired you can use the bringToFront method of L.FeatureLayer:
Brings the layer group to the top of all other layers.
http://leafletjs.com/reference.html#featuregroup-bringtofront
map.on('overlayadd', function () {
dHMT.dataValueLayer.bringToFront();
});

Highlight area programmatically - Chart.js

I'm using Chart.js (doughnut chart) and I would like to ask if is there any choice to highlight area programmatically? I mean - when I click on a button, then the specific area will be highlighted.
Thanks for your reply.
Just loop through the doughnut segments, match based on label and swap / restore the fill color.
function highlight(label) {
myDoughnutChart.segments.forEach(function (segment, i) {
if (segment.label == label) {
if (segment.fillColor == segment.highlightColor)
segment.restore(["fillColor"]);
else
segment.fillColor = segment.highlightColor;
myDoughnutChart.render();
}
})
}
Fiddle - http://jsfiddle.net/35of1Lzg/
I've disabled tooltips and the tooltip highlight by setting tooltipEvents = [], but if you want them back you can always remove it from the options, but then hover / mouseout and the button click will do the same thing.
To popup the tooltip too when highlighting use this
function highlight(label) {
myDoughnutChart.segments.forEach(function (segment) {
if (segment.label == label) {
if (segment.fillColor == segment.highlightColor)
segment.restore(["fillColor"]);
else
segment.fillColor = segment.highlightColor;
myDoughnutChart.render()
}
})
var activeSegements = [];
myDoughnutChart.segments.forEach(function (segment) {
if (segment.fillColor === segment.highlightColor) {
activeSegements.push(segment)
}
});
myDoughnutChart.showTooltip(activeSegements, true)
}
http://jsfiddle.net/jdr5381e/
FYI the fiddles are no longer working, you'll need to replace the links to the Chart.min.js
I used these to get them working: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js