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 22:12, 8 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() {
    mw.loader.using( [ "mediawiki.api" ] ).then( function () {

        // Determine the name of this page's associated talk page.
        // (If we're already on one, then talkPageName is set to wgPageName.)
        var talkPageName;
        var currNamespaceNum = mw.config.get( "wgNamespaceNumber" );
        if( currNamespaceNum % 2 === 0 ) {
            talkPageName = mw.config.get( "wgFormattedNamespaces" )[ currNamespaceNum + 1 ] +
                ":" + mw.config.get( "wgTitle" );
        } else {
            talkPageName = mw.config.get( "wgPageName" );
        }

        // 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
            var countEl = document.createElement( "span" );
            countEl.style.cssText = "padding-top: 1.25em; background: 0; font-size: 0.8em; margin-right: 0.625em";

            // 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*\1==\s*$/gm;
                var headerMatchList = text.match( HEADER_RE );
                var headerCount = headerMatchList ? headerMatchList.length : 0;
                countEl.style.cssText += "; color: blue";
                countEl.textContent = "(" + headerCount + ")";
            }

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