[go: nahoru, domu]

Jump to content

User:Ainali/viewStats.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// ==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);

})();