User:Surjection/linkLanguageHeaders.js

"use strict";

// //

(function linkLanguageHeaders {   var CACHE_DURATION = 24 * 60 * 60; // 24 hours

var ALLOWED_NAMESPACES = [ 0,     // main 118    // Reconstruction ];

function categoryNameFromLanguageName(name) { return (name + " language").replace(/ Language language$/, " Language"); }

function getLanguageCodesByCanonicalName(callback, cacheDuration) { var KEY = "enwiktLanguageCanonicalNamesJson"; var timeNow = new Date.getTime * 1e-3; try { var cachedData = JSON.parse(localStorage.getItem(KEY)); if (timeNow - cachedData.timestamp < cacheDuration) { callback(cachedData.data); return; }       } catch (e) { }

var request = new mw.Api.get({           "action": "parse",            "page": "Module:languages/canonical names.json",            "prop": "wikitext",            "formatversion": 2,            "format": "json"        }); request.done(function(response) {           var languageData = JSON.parse(response.parse.wikitext);            callback(languageData);            localStorage.setItem(KEY, JSON.stringify({                timestamp: timeNow,                data: languageData            }));        }); }

function linkLanguageHeaders(codeByCanonicalName) { $("#mw-content-text h2 .mw-headline").each(function {           var headline = $(this);            var languageName = headline.text;            var languageCode = codeByCanonicalName[languageName];            if (languageCode) {                var categoryName = categoryNameFromLanguageName(languageName);                var pageName = mw.config.get("wgFormattedNamespaces")[14] + ":" + categoryName;                headline.html($("", {                    text: languageName,                    title: languageName + " [" + languageCode + "]",                    href: mw.config.get("wgArticlePath").replace("$1", encodeURIComponent(pageName.replace(/ /g, "_")))                }));            }        }); }

mw.hook("wikipage.content").add(function($) {       if (mw.config.get("wgAction") === "view" && ALLOWED_NAMESPACES.indexOf(mw.config.get("wgNamespaceNumber")) >= 0) {           getLanguageCodesByCanonicalName(function (codeByCanonicalName) { linkLanguageHeaders(codeByCanonicalName); }, CACHE_DURATION);       }    }); });

//