website/js/customElements/ntpGraph.js
2021-04-13 10:37:20 +02:00

74 lines
No EOL
2.3 KiB
JavaScript

import chart from 'chart.js'
let graphIndexCounter = 0;
class NtpGraph extends HTMLElement {
constructor() {
super();
let ip = this.getAttribute("data-server-ip");
this.innerHTML = `
<span id="${graphIndexCounter}-Banner" data-index="${graphIndexCounter}" class="ntpBanner">${ip}</span>
<span id="${graphIndexCounter}-Content" class="ntpContent">
<a target="_blank" href="https://www.ntppool.org/scores/${ip}" class="linkToNtpPool">Server auf dem NTP Pool anzeigen</a>
<canvas id="${graphIndexCounter}-Delay"></canvas>
<canvas id="${graphIndexCounter}-Score"></canvas>
</span>
`;
let currentIndex = graphIndexCounter;
graphIndexCounter++;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4){
let rawData = JSON.parse(xhr.responseText);
let x = [];
let yScore = [];
let yDelay = [];
rawData["history"].forEach((entry, index) => {
let date = new Date(entry["ts"] * 1000).toLocaleDateString();
if(index % 10 !== 0){
date = "";
}
x.push(date);
yScore.push(entry["score"]);
yDelay.push(entry["offset"]);
});
this.drawPlot(currentIndex + "-Delay", x, yDelay, "Delay");
this.drawPlot(currentIndex + "-Score", x, yScore, "Score");
}
}
xhr.open("GET", "https://www.ntppool.org/scores/" + ip + "/json?monitor=*&limit=800");
xhr.send();
}
drawPlot(elementName, x, y, title){
let ctx = document.getElementById(elementName).getContext('2d');
new Chart(ctx, {
type: 'line',
responsive: true,
scaleShowVerticalLines: false,
showTooltips: false,
data: {
labels: x,
datasets: [{
label: title,
data: y,
borderColor: '#199a87',
fill: false,
radius: 0,
}]
},
});
}
}
customElements.define("jl-ntp-graph", NtpGraph);