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.
/***********************************************************************************/
/*                                                                                 */
/*							  Wikipedia Edit Counter 							   */
/*							Developed by User:Jeeputer							   */
/*																				   */
/***********************************************************************************/

if (mw.config.get('wgTitle') === mw.config.get('wgUserName') && mw.config.get('wgNamespaceNumber') === 2) {

    $(function(){
        if (!$('#t-contributions').length && mw.config.get('wgNamespaceNumber') == 2) {
            alert('Missing "User contributions" link in the side menu');
            return;
        }
        var $editCountLink = $('<a>Edit counter v2.0</a>').attr({
            id: 't-editcounter',
            href: '#',
            title: 'Run edit counter script'
        });
        $('#t-contributions').after($('<li></li>').html($editCountLink));
        $('#t-editcounter').click(function() {
            $('#t-editcounter').text('Processing…');
            mw.notify($('<span>Fetching your contributions...<br/>' + 
	            'Please don\'t close this tab.' +
	            ' Once finished, the script will let you know.</span>'),
	            	{
	            		title: 'Edit Counter v2.0'
	            	}
	        	);
            var namespaces = mw.config.get('wgFormattedNamespaces');
                namespaces[0] = 'Main';
            var namespaceID = function(ns) {
                return mw.config.get('wgNamespaceIds')[ns.replace(' ', '_')];
            };
            var userName = mw.config.get('wgUserName');
            
            var contribs = [];
                config = {};
            var API = new mw.Api({
                ajax: {
                    headers: {
                        'Api-User-Agent': 'editCounter/0.1.1' +
                            ' ( https://en.wikipedia.org/wiki/User:Jeeputer/editCounter )'
                    }
                }
            });
        
            config.isDone = false;
            
            var grabData = function() {
        
                var checkData = function() {
                    if (config.isDone) {
                        //all done - log totals
                        createTable();
                    }
                };
                
                var processQuery = function(result) {
                    var usercontrib = result.query.usercontribs,
                		uc, ns;
                	for (uc in usercontrib) {
                        ns = usercontrib[uc].ns;
                        contribs.push({ns: ns});
                	}
                    if (result.continue) {
                        doQuery($.extend(contribsQuery, result.continue));
                        return;
                    } else {
                        config.isDone = true;
                    }
                    checkData();
                };
                var contribsQuery = {
                    action: 'query',
            		format: 'json',
            		list: 'usercontribs',
            		ucuser: userName,
                    uclimit: 500
                };
                
                var doQuery = function(q) {
                    API.get(q).done(processQuery);
                };
                
                doQuery(contribsQuery);
            };
            grabData();
            var createTable = function() {
                var contribsByNs = {},
                    i;
                for (i = 0; i < contribs.length; i++) {
                    if (contribs[i].ns in contribsByNs) {
                        contribsByNs[contribs[i].ns]++;
                    } else {
                        contribsByNs[contribs[i].ns] = 1;
                    }
                }
        
                var incrHeaders = function(obj) {
                    var namespacesLocalNames = Object.keys(obj);
                    var editCountByNamespaceNum = Object.values(obj);
                    var fullTable = '',
                        tableStart = '{| ',
                        tableEnd = '|}',
                        contribLink = '[' + mw.config.get('wgServer') +
							mw.config.get('wgScriptPath') +
							'/index.php?title=Special%3AContributions&target=' +
							encodeURIComponent(userName) + '&namespace=',
                        contribLinked = '',
                        bracesLeft = '{{',
                        bracesRight = '}}',
                        dateFormat = 'j F Y',
                        timeStamp = bracesLeft + 'subst:#time:' + dateFormat + bracesRight,
                        mainTableAttrib = 'class="wikitable" style="margin: ' +
                        	'0 auto 1em; font-size: small; text-align: center"\n',
                        tableCaptionAttrib = '|+ style="caption-side: bottom; ' +
        					'font-size: x-small; font-weight: normal" | ',
                        tableCaption = '[[' + 'User:Jeeputer/editCounter|' +
        					'Last updated: ' + timeStamp + ']]\n',
                        plainLinksAttrib = '|- class="plainlinks" \n',
                        headersStr = '',
                        colsString = '',
                        totalCount = mw.config.get('wgUserEditCount');
                        
                    for (var j = 0; j < namespacesLocalNames.length; j++) {
                        headersStr += '! ' + namespaces[namespacesLocalNames[j]] + '\n';
                    }
                    for (var c = 0; c < editCountByNamespaceNum.length; c++) {
                        contribLinked = contribLink +
                        				Object.keys(namespacesLocalNames)[c] + ' ' +
                            			mw.language.convertNumber(editCountByNamespaceNum[c]) + ']';
                        colsString += '| ' + contribLinked + '\n';
                    }
                    colsString = colsString + '| [[Special:Contributions/' + userName +
                    			 '|' + mw.language.convertNumber(totalCount) + ']]\n';
        
                    fullTable = tableStart +
                    			mainTableAttrib +
                    			tableCaptionAttrib +
                    			tableCaption +
                    			headersStr + '! Total\n' +
                    			plainLinksAttrib +
                    			colsString +
                    			tableEnd;
                    
                    updateCountPage(fullTable);
                };
                
        
                incrHeaders(contribsByNs);
            };
            var updateCountPage = function (table) {
                var fullPageName = 'User:' + userName + '/edit count';
                var editParams = {
                    format: 'json',
                    action: 'edit',
                    title: fullPageName,
                    text: table,
                    summary: '[[User:Jeeputer/editCounter|updated!]]',
                    bot: '1',
                    minor: '1',
                    recreate: '1'
                };
                API.postWithToken('csrf', editParams).done(function (data) {
                    if (data.edit.result != 'Success') {
                        $('#t-editcounter').text('Not done!').css('color', 'red');
                        mw.notify('Failed to update you edit count!', {
                        	title: 'Edit Counter v2.0',
                        	type: 'error'
                        });
                    } else {
                        $('#t-editcounter').text('Done!').css('color', 'green');
                        mw.notify($('<span>Success counting!<br/>You <a href="/wiki/User:' +
                        userName + '/edit_count">Edit count subpage</a> has been edited. (<a href="/wiki/Special:Diff/' +
                        data.edit.newrevid + '">Diff</a>)</span>'), {
                        	title: 'Edit Counter v2.0',
                        	type: 'success',
                        	autoHideSeconds: 20
                        });
                        alert('Edit Counter v2.0 finished counting your edits! You may close the tab now.');
                    }
                });
            };
        });
    
    });
}