Jump to content

User:Opencooper/talkCount.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Opencooper (talk | contribs) at 05:23, 25 May 2019 (Undid revision 898669507 by Opencooper (talk)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
// Shows the number of discussions on the talk page
// Namespace # reference: https://www.mediawiki.org/wiki/Manual:Namespace#Built-in_namespaces

function setup() {
    // If we're not reading an article, do nothing
    if (!(mw.config.get('wgAction') === 'view'
          && mw.config.get('wgIsArticle')
          && !location.search.split('oldid=')[1] // Old revision
          && !mw.config.get("wgIsMainPage"))) {
        return;
    }

    // Check if we're on a talk page
    var namespace = mw.config.get( 'wgNamespaceNumber' );
    if (namespace % 2 == 1) { // All talk namespaces have odd numbers
    	return;
    }

    // Check if talk page is a redlink
    if ($("#ca-talk.new").length !== 0) {
        return;
    }

    var talkUrl = $("#ca-talk a").attr("href");
    var talkTitle = talkUrl.split("/wiki/")[1];
    talkTitle = decodeURI(talkTitle);
    // Mediawiki encodes these while decodeURI doesnt reverse it
    talkTitle = talkTitle.replace(/%26/, "&").replace(/%2B/, "+").replace(/%3D/, "=").replace(/%3F/, "?");

    // Get parsed talk page section info
    // API docs: https://en.wikipedia.org/w/api.php?action=help&modules=parse
    var apiUrl = location.origin + "/w/api.php";
    $.ajax({
        url: apiUrl,
        data: {
            action: "parse",
            format: "json",
            page: talkTitle,
            prop: "sections"
        },
        success: countSections
    });
}

function countSections(response) {
    var sectionsCount = response.parse.sections.length;

    var sectionTitles = "";
    for (var i = 0; i < sectionsCount; i++) {
        sectionHeader = response.parse.sections[i].line;
        sectionHeader = sectionHeader.replace(/'/g, "&apos;"); // escape
        sectionTitles += i+1 + ". " + sectionHeader;

        if (i != sectionsCount-1) {
            sectionTitles += "\n";
        }
    }

    var countHTML = " <small id='talkCount' title='"+ sectionTitles + "'>("
                    + sectionsCount + ")</small>";
    $("#ca-talk a").append(countHTML);
}

setup();