User:Ainali/viewStats.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Ainali/viewStats. |
// ==UserScript==
// @name Wikipedia View Stats with Sparkline
// @namespace http://en.wikipedia.org
// @version 1.0
// @description Add view stats with sparkline to Wikipedia articles
// @author Ainali
// @match https://*.wikipedia.org/wiki/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Function to get page views data
function getPageViews(title, callback) {
const today = new Date();
const endDate = today.toISOString().slice(0, 10).replace(/-/g, '');
const startDate = new Date(today.setDate(today.getDate() - 30)).toISOString().slice(0, 10).replace(/-/g, '');
const apiUrl = `https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/${title}/daily/${startDate}/${endDate}`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
if (data.items) {
callback(data.items);
} else {
console.log('No data found.');
}
})
.catch(error => console.error('Error fetching page views:', error));
}
// Function to create a sparkline using Canvas
function createSparkline(views) {
// Create a canvas element
const canvas = document.createElement('canvas');
canvas.width = 80; // Reduced width of the sparkline to fit better
canvas.height = 20; // Reduced height of the sparkline
const ctx = canvas.getContext('2d');
// Get the views data as an array of numbers
const viewValues = views.map(day => day.views);
// Determine the max value for scaling
const maxValue = Math.max(...viewValues);
// Calculate the width and height scaling
const xStep = canvas.width / (viewValues.length - 1);
const yScale = (canvas.height - 2) / maxValue;
// Draw the sparkline
ctx.beginPath();
ctx.moveTo(0, canvas.height - viewValues[0] * yScale);
viewValues.forEach((value, index) => {
ctx.lineTo(index * xStep, canvas.height - value * yScale);
});
ctx.strokeStyle = '#007bff'; // Line color
ctx.lineWidth = 1.5; // Line width
ctx.stroke();
return canvas;
}
// Function to display page views and append sparkline
function displayPageViews(views) {
const lastDay = views[views.length - 1].views;
const previousDay = views[views.length - 2].views;
const streak = lastDay > previousDay ? "↑" : "↓";
const viewData = `${lastDay} views (${streak}${Math.abs(lastDay - previousDay)} from yesterday)`;
const viewContainer = document.createElement('div');
viewContainer.style = 'display: inline-block; padding: 2px 5px; background-color: #f8f9fa; font-size: 12px; margin-left: 10px;';
const textSpan = document.createElement('span');
textSpan.textContent = viewData;
viewContainer.appendChild(textSpan);
const sparkline = createSparkline(views);
viewContainer.appendChild(sparkline);
// Insert the viewContainer after the "Talk" tab
const talkTab = document.getElementById('ca-talk');
if (talkTab && talkTab.parentNode) {
talkTab.parentNode.insertBefore(viewContainer, talkTab.nextSibling);
}
}
// Fetch and display page views and sparkline for the current page
const title = mw.config.get('wgPageName');
getPageViews(title, displayPageViews);
})();