Jump to content

User:Enterprisey/talk-tab-count.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Enterprisey (talk | contribs) at 05:21, 9 January 2018 (Updating User:Enterprisey/talk-tab-count.js from local version). 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.
$( function() {

    // Build element that will hold the count
    var countEl = document.createElement( "span" );
    countEl.style.cssText = "padding-top: 1.25em; background: 0; font-size: 0.8em; margin-right: 0.625em";
    countEl.textContent = "(?)";

    // Insert this count into the talk page tab, early
    var talkTab = document.getElementById( "ca-talk" );
    talkTab.childNodes[0].appendChild( countEl );

    // Determine the name of this page's associated talk page.
    // (If we're already on one, then talkPageName is set to wgPageName.)
    var talkPageNamespaceNum = 2 * Math.floor( mw.config.get( "wgNamespaceNumber" ) / 2 ) + 1;
    var talkPageNamespace = mw.config.get( "wgFormattedNamespaces" )[ talkPageNamespaceNum ];
    var talkPageName = talkPageNamespace + ":" + mw.config.get( "wgTitle" );

    mw.loader.using( [ "mediawiki.api" ] ).then( function () {

        // Get the text of the talk page and count the level-2 headers
        ( new mw.Api() ).get( {
            prop: 'revisions',
            rvprop: 'content',
            rvlimit: 1,
            titles: talkPageName
        } ).done( function ( data ) {
            if ( !data.query || !data.query.pages ) return;
            var pageid = Object.getOwnPropertyNames( data.query.pages )[0],
                revisions = data.query.pages[pageid].revisions;

            // Begin building the count element

            // Set the text and color based on the talk page's state
            if( revisions === undefined ) {

                // The talk page does not exist
                countEl.style.cssText += "; color: #a55858";
                countEl.textContent = "(0)";
            } else {
                var text = revisions[0]["*"];
                var HEADER_RE = /^\s*==\s*[^=]+?\s*==\s*$/gm;
                var headerMatchList = text.match( HEADER_RE );
                var headerCount = headerMatchList ? headerMatchList.length : 0;
                countEl.style.cssText += "; color: #0645ad";
                countEl.textContent = "(" + headerCount + ")";
            }

        } );
    } );
} );