Aller au contenu

MediaWiki:Gadget-Util.js

De Wiki Undertale FR

Note : après avoir publié vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou appuyez sur Ctrl + F5 ou Ctrl + R (⌘ + R sur un Mac).
  • Google Chrome : appuyez sur Ctrl + Maj + R (⌘ + Shift + R sur un Mac).
  •  Edge : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl + F5.
function getTitleFromUrl(url) {
    if (url.searchParams.has('title')) {
        return new mw.Title(url.searchParams.get('title'));
    }
    const articlePrefix = mw.util.getUrl('');
    if (url.pathname.startsWith(articlePrefix)) {
        return new mw.Title(decodeURIComponent(url.pathname.replace(articlePrefix, '')));
    }
}

function getSpecialPageTarget(url, title, aliases) {
    if (title.namespace !== -1) {
        return;
    }
    const [specialPageName, ...subpages] = title.title.split('/');
    const target = subpages.join('/') || url.searchParams.get('target');
    if (target && aliases.includes(specialPageName.toLowerCase())) {
        return target;
    }
}

function parseReasonDropdown(message) {
    const reasons = [];
    for (const line of mw.msg(message).trim().split('\n')) {
        const match = line.match(/^\s*(\*+)\s*(.*?)\s*$/u);
        if (!match) {
            continue;
        }
        const level = match[1].length;
        const reason = match[2];
        if (level === 1) {
            reasons.push({
                label: reason,
                items: []
            });
        } else if (level === 2) {
            const item = {
                label: reason,
                value: reason
            };
            if (reasons[reasons.length - 1].items) {
                reasons[reasons.length - 1].items.push(item);
            } else {
                reasons.push(item);
            }
        }
    }
    return reasons;
}

const TIME_UNITS = {
    year: 31536000,
    month: 2592000,
    week: 604800,
    day: 86400,
    hour: 3600,
    minute: 60,
    second: 1,
};

function timeSince(date) {
    if (!window.Intl || !window.Intl.RelativeTimeFormat) {
        return '';
    }
    const rtf = new Intl.RelativeTimeFormat(mw.config.get('wgUserLanguage'), {
        numeric: 'auto'
    });
    const seconds = Math.floor((new Date(date).getTime() - Date.now()) / 1000);
    for (const [unit, interval] of Object.entries(TIME_UNITS)) {
        if (Math.abs(seconds) >= interval) {
            return rtf.format(Math.round(seconds / interval), unit);
        }
    }
    return rtf.format(-0, 'second');
}

module.exports = {
    getTitleFromUrl,
    getSpecialPageTarget,
    parseReasonDropdown,
    timeSince,
};