269 lines
8.3 KiB
JavaScript
269 lines
8.3 KiB
JavaScript
/* Analytics dashboard: visitor location map + location trend chart.
|
|
*
|
|
* Both charts read their data from JSON <script> blocks embedded by
|
|
* templates/admin/analytics.html, so there is no extra API request and no
|
|
* chart library to load. Leaflet (vendored under /static/vendor/leaflet) is
|
|
* used for the map only when it is present.
|
|
*/
|
|
(function () {
|
|
"use strict";
|
|
|
|
var PALETTE = [
|
|
"#1f6feb", "#e36209", "#2ea043", "#8250df", "#cf222e", "#8b949e",
|
|
];
|
|
|
|
function readJSON(id) {
|
|
var el = document.getElementById(id);
|
|
if (!el) return null;
|
|
try {
|
|
return JSON.parse(el.textContent);
|
|
} catch (err) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function dayLabel(iso) {
|
|
var parts = String(iso).split("-");
|
|
var date = new Date(Date.UTC(+parts[0], +parts[1] - 1, +parts[2]));
|
|
return date.toLocaleDateString(undefined, {
|
|
month: "short", day: "numeric", timeZone: "UTC",
|
|
});
|
|
}
|
|
|
|
function niceMax(value) {
|
|
if (value <= 4) return 4;
|
|
var power = Math.pow(10, Math.floor(Math.log10(value)));
|
|
var steps = [1, 2, 2.5, 5, 10];
|
|
for (var i = 0; i < steps.length; i++) {
|
|
if (steps[i] * power >= value) return steps[i] * power;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function drawTrend() {
|
|
var data = readJSON("location-trend-data");
|
|
var canvas = document.getElementById("location-trend-chart");
|
|
if (!data || !canvas || !data.series || !data.series.length) return;
|
|
|
|
var wrap = canvas.parentNode;
|
|
var tooltip = document.createElement("div");
|
|
tooltip.className = "chart-tooltip";
|
|
tooltip.hidden = true;
|
|
wrap.appendChild(tooltip);
|
|
|
|
var legend = document.getElementById("location-trend-legend");
|
|
data.series.forEach(function (series, index) {
|
|
var item = document.createElement("span");
|
|
var swatch = document.createElement("span");
|
|
swatch.className = "swatch";
|
|
swatch.style.backgroundColor = PALETTE[index % PALETTE.length];
|
|
item.appendChild(swatch);
|
|
item.appendChild(document.createTextNode(series.name));
|
|
legend.appendChild(item);
|
|
});
|
|
|
|
var PAD = { top: 14, right: 14, bottom: 30, left: 44 };
|
|
var HEIGHT = 280;
|
|
var hoverIndex = -1;
|
|
|
|
function render() {
|
|
var width = Math.max(320, wrap.clientWidth);
|
|
var dpr = window.devicePixelRatio || 1;
|
|
canvas.width = Math.round(width * dpr);
|
|
canvas.height = Math.round(HEIGHT * dpr);
|
|
canvas.style.width = width + "px";
|
|
canvas.style.height = HEIGHT + "px";
|
|
|
|
var ctx = canvas.getContext("2d");
|
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
ctx.clearRect(0, 0, width, HEIGHT);
|
|
|
|
var plotW = width - PAD.left - PAD.right;
|
|
var plotH = HEIGHT - PAD.top - PAD.bottom;
|
|
var max = 0;
|
|
data.series.forEach(function (series) {
|
|
series.data.forEach(function (value) {
|
|
if (value > max) max = value;
|
|
});
|
|
});
|
|
max = niceMax(max);
|
|
var count = data.labels.length;
|
|
|
|
function xAt(index) {
|
|
return PAD.left + (count === 1 ? plotW / 2 : (index / (count - 1)) * plotW);
|
|
}
|
|
function yAt(value) {
|
|
return PAD.top + plotH - (value / max) * plotH;
|
|
}
|
|
|
|
ctx.strokeStyle = "#e5e7eb";
|
|
ctx.fillStyle = "#6b7280";
|
|
ctx.font = "12px system-ui, -apple-system, sans-serif";
|
|
ctx.lineWidth = 1;
|
|
ctx.textAlign = "right";
|
|
ctx.textBaseline = "middle";
|
|
for (var tick = 0; tick <= 4; tick++) {
|
|
var tickValue = (max / 4) * tick;
|
|
var tickY = yAt(tickValue);
|
|
ctx.beginPath();
|
|
ctx.moveTo(PAD.left, tickY);
|
|
ctx.lineTo(width - PAD.right, tickY);
|
|
ctx.stroke();
|
|
ctx.fillText(String(Math.round(tickValue)), PAD.left - 8, tickY);
|
|
}
|
|
|
|
ctx.textAlign = "center";
|
|
ctx.textBaseline = "top";
|
|
var stride = Math.max(1, Math.ceil(count / 7));
|
|
for (var i = 0; i < count; i += stride) {
|
|
ctx.fillText(dayLabel(data.labels[i]), xAt(i), HEIGHT - PAD.bottom + 8);
|
|
}
|
|
|
|
data.series.forEach(function (series, index) {
|
|
ctx.strokeStyle = PALETTE[index % PALETTE.length];
|
|
ctx.lineWidth = 2;
|
|
ctx.lineJoin = "round";
|
|
ctx.beginPath();
|
|
series.data.forEach(function (value, i) {
|
|
var x = xAt(i);
|
|
var y = yAt(value);
|
|
if (i === 0) ctx.moveTo(x, y);
|
|
else ctx.lineTo(x, y);
|
|
});
|
|
ctx.stroke();
|
|
});
|
|
|
|
if (hoverIndex >= 0) {
|
|
var hoverX = xAt(hoverIndex);
|
|
ctx.strokeStyle = "rgba(31, 111, 235, 0.35)";
|
|
ctx.lineWidth = 1;
|
|
ctx.beginPath();
|
|
ctx.moveTo(hoverX, PAD.top);
|
|
ctx.lineTo(hoverX, HEIGHT - PAD.bottom);
|
|
ctx.stroke();
|
|
|
|
var lines = [dayLabel(data.labels[hoverIndex])];
|
|
data.series.forEach(function (series, index) {
|
|
var value = series.data[hoverIndex] || 0;
|
|
if (!value) return;
|
|
ctx.fillStyle = PALETTE[index % PALETTE.length];
|
|
ctx.beginPath();
|
|
ctx.arc(hoverX, yAt(value), 3, 0, Math.PI * 2);
|
|
ctx.fill();
|
|
lines.push(series.name + ": " + value);
|
|
});
|
|
tooltip.textContent = lines.join(" \u00b7 ");
|
|
tooltip.hidden = false;
|
|
var left = Math.min(Math.max(hoverX + 10, 8), width - tooltip.offsetWidth - 8);
|
|
tooltip.style.left = left + "px";
|
|
tooltip.style.top = PAD.top + "px";
|
|
} else {
|
|
tooltip.hidden = true;
|
|
}
|
|
}
|
|
|
|
canvas.addEventListener("mousemove", function (event) {
|
|
var rect = canvas.getBoundingClientRect();
|
|
var plotW = Math.max(1, rect.width - PAD.left - PAD.right);
|
|
var count = data.labels.length;
|
|
var ratio = (event.clientX - rect.left - PAD.left) / plotW;
|
|
var index = Math.round(ratio * (count - 1));
|
|
index = Math.max(0, Math.min(count - 1, index));
|
|
if (index !== hoverIndex) {
|
|
hoverIndex = index;
|
|
render();
|
|
}
|
|
});
|
|
canvas.addEventListener("mouseleave", function () {
|
|
hoverIndex = -1;
|
|
render();
|
|
});
|
|
|
|
var resizeTimer = null;
|
|
window.addEventListener("resize", function () {
|
|
clearTimeout(resizeTimer);
|
|
resizeTimer = setTimeout(render, 150);
|
|
});
|
|
|
|
render();
|
|
}
|
|
|
|
function escapeHtml(value) {
|
|
return String(value == null ? "" : value)
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, """)
|
|
.replace(/'/g, "'");
|
|
}
|
|
|
|
function initMap() {
|
|
var points = readJSON("visitor-map-data") || [];
|
|
var container = document.getElementById("visitor-map");
|
|
if (!container || typeof L === "undefined") return;
|
|
|
|
var map = L.map(container, { minZoom: 2, worldCopyJump: true }).setView([20, 0], 2);
|
|
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
|
|
maxZoom: 19,
|
|
attribution:
|
|
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
|
}).addTo(map);
|
|
|
|
// Keep the world map visible even before the first located visit.
|
|
if (!points.length) {
|
|
setTimeout(function () { map.invalidateSize(); }, 0);
|
|
return;
|
|
}
|
|
|
|
var maxVisits = 1;
|
|
points.forEach(function (point) {
|
|
if (point.visits > maxVisits) maxVisits = point.visits;
|
|
});
|
|
|
|
var bounds = [];
|
|
points.forEach(function (point) {
|
|
var radius = 5 + 16 * Math.sqrt(point.visits / maxVisits);
|
|
var label = [point.city, point.region, point.country]
|
|
.filter(Boolean)
|
|
.join(", ");
|
|
L.circleMarker([point.lat, point.lon], {
|
|
radius: radius,
|
|
color: "#1f6feb",
|
|
weight: 1.5,
|
|
fillColor: "#1f6feb",
|
|
fillOpacity: 0.3,
|
|
})
|
|
.addTo(map)
|
|
.bindPopup(
|
|
"<strong>" + escapeHtml(label || "Unknown location") + "</strong><br>" +
|
|
escapeHtml(point.visits) + " visit(s) from " +
|
|
escapeHtml(point.visitors) + " visitor(s)"
|
|
);
|
|
bounds.push([point.lat, point.lon]);
|
|
});
|
|
|
|
if (bounds.length === 1) {
|
|
map.setView(bounds[0], 5);
|
|
} else {
|
|
map.fitBounds(L.latLngBounds(bounds).pad(0.25), { maxZoom: 6 });
|
|
}
|
|
setTimeout(function () {
|
|
map.invalidateSize();
|
|
}, 0);
|
|
window.addEventListener("resize", function () {
|
|
map.invalidateSize();
|
|
});
|
|
}
|
|
|
|
function start() {
|
|
drawTrend();
|
|
initMap();
|
|
}
|
|
|
|
if (document.readyState === "loading") {
|
|
document.addEventListener("DOMContentLoaded", start);
|
|
} else {
|
|
start();
|
|
}
|
|
})();
|