User:SD0001/draft-sort-burst.js - Wikipedia


Article Images

Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump.
This code will be executed when previewing this page.

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.

// Extended from [[User:Enterprisey/draft-sorter.js]]

//<nowiki>
$.when(mw.loader.using(['jquery.chosen', 'mediawiki.util']), $.ready).then(function() {
    mw.loader.load( "mediawiki.ui.input", "text/css" );

    if ( mw.config.get( "wgNamespaceNumber" ) !== 118 ) return;

	const WIKIPROJECT_LIST = "Wikipedia:WikiProject Articles for creation/WikiProject templates.json";

	$( mw.util.addPortletLink('p-cactions', '#', 'Draft-sort', 'ptx-draftsort', 'Add WikiProject tags') ).click(function(e) {
		e.preventDefault();
		draftsort();
	} );

	var draftsort = function ( ) {

        // If it's already there, don't duplicate
        if ( $( "#draft-sorter-wrapper" ).length ) return;

        // Construct the form
        var form = $( "<div>" )
            .attr( "id", "draft-sorter-wrapper" )
            .css( { "background-image": "url(https://upload.wikimedia.org/wikipedia/commons/b/b8/OOjs_UI_icon_tag-progressive.svg)",
                    "background-repeat": "no-repeat",
                    "background-position-y": "center",
                    "background-size": "50px",
                    "margin": "1em auto",
                    "border": "thin solid #BBB",
                    "padding": "0.5em 0",
                    "padding-left": "50px",
                    "display": "inline-block",
                    "border-radius": "0.25em"
            } )
            .append( $( "<span>" )
                .text( "Loading form..." )
                .css( "color", "gray" ) );

        var select = $( "<select>" )
            .attr( "id", "draft-sorter-form" )
			.attr( "multiple", "multiple" );

		$.getJSON( mw.config.get( 'wgServer' ) + "/w/index.php?title=" +
        encodeURIComponent(WIKIPROJECT_LIST) + "&action=raw&ctype=text/json" ).done( function ( data ) {
            $.each( data, function ( name, template ) {
            	select.append( $( "<option>" )
            	    .attr( "value", template )
            	    .text( name ) );
            } );
            form.hide();
            form.empty();
            form.append( $( "<span>" )
                .text( "Tag WikiProjects: " )
                .css( {
                	"font-size": "115%",
                	"font-weight": "bold"
                } ) );
            form.append( select );
            form.append( $( "<button>" )
                .text( "Submit" )
                .addClass( "mw-ui-button" )
                .addClass( "mw-ui-progressive" )
                .addClass( "mw-ui-big" )
                .css( "margin-left", "0.25em" )
                .attr( "accesskey", "s" )
                .click( submit ) );
            form.append( $( "<button>" )
				.addClass( "mw-ui-button mw-ui-destructive mw-ui-quiet" )
				.text( "Cancel" )
				.click( function () {
					$( "#draft-sorter-wrapper" ).remove();
				} ) );

			// add skip button only if in burst mode
			if (mw.util.getParamValue('draftsorttrigger')) {
				form.append( $('<button>')
					.addClass('mw-ui-button')
					.addClass('mw-ui-destructive')
					.addClass('mw-ui-quiet')
					.addClass('draft-sort-skip')
					.text('Skip')
				);
			}
            form.show();
            $( select ).chosen( {
            	"placeholder_text_multiple": "Select some WikiProjects"
			} );

        } ).catch(console.log);	

        // Add the form to the page
        form.insertAfter( "#siteSub" );
        
        $(".chosen-search-input").focus();

        // The submission function
        var submit = function () {
        	var newTags = $( "#draft-sorter-form").val();
			//console.log( newTags );

        	var statusList = $( "<ul>" )
				.appendTo( "#draft-sorter-wrapper" )
				.append( $( "<li>" ).text( "Saving " + newTags.length + " new tags." ) );

        	var showStatus = function ( status ) {
        		return $( "<li>" )
        		    .text( status )
        		    .appendTo( statusList );
			};

        	var newText = "";
        	newTags.forEach( function ( element ) {
        		newText += "{{" + element + "}}\n";
			} );

        	$.ajax( {
                url: mw.util.wikiScript( 'api' ),
                type: 'POST',
                dataType: 'json',
                data: {
                    format: 'json',
                    action: 'edit',
                    title: "Draft talk:" + mw.config.get( 'wgTitle' ),
                    summary: "Adding WikiProject tags ([[User:SD0001/draft-sort-burst|draft-sort-burst]])",
                    watchlist: typeof draft_sort_burst_watchlistOption === 'undefined' ? "nochange" : draft_sort_burst_watchlistOption,
                    token: mw.user.tokens.get( 'csrfToken' ),
                    prependtext: newText
                }
        	} ).done( function ( data ) {
        		if ( data && data.edit && data.edit.result && data.edit.result === "Success" ) {
        			showStatus( "Edit saved successfully! (" )
                        .append( $( "<a>" )
                            .text( "reload" )
                            .attr( "href", "#" )
                            .click( function () { document.location.reload( true ); } ) )
						.append( ")" );
					var event = new Event('draft_sort:saved');
					document.dispatchEvent(event);
        		} else {
        			showStatus( "Couldn't save due to error: " + JSON.stringify( data ) );
        		}
        	} ).fail( function ( error ) {
        		showStatus( "Couldn't save due to error: " + JSON.stringify( error ) );
        	} );
        };
    }


	$(mw.util.addPortletLink('p-cactions', '#', 'Draft-sort (burst)', 'ptx-draftsortburst', 'Add WikiProject tags to drafts in burst mode')).click(function(e) {
		e.preventDefault();
		burstmode();
	});

	if (mw.util.getParamValue('draftsorttrigger')) {
		burstmode();
	}

	function burstmode() {

		draftsort();

		var nextDraft, cmcontinue;
		var api = new mw.Api();
		var query = {
			"action": "query",
			"list": "categorymembers",
			"cmtitle": "Category:Pending_AfC_submissions",
			"cmprop": "title",
			"cmnamespace": "118",
			"cmlimit": "50",
			"cmsort": "sortkey",
			"cmdir": "ascending",
			"cmstartsortkeyprefix": "P"
		};

		function checkTalkPages(r) {
			//console.log('in checkTalkPages');
			//console.log(r);
			if (r && r.query && r.query.categorymembers) {

				cmcontinue = r.continue.cmcontinue;
				var draftTalkPages = r.query.categorymembers.map(function(e) {
					return e.title.replace(/^Draft:/, 'Draft talk:');
				});
				return api.get({
					action: 'query',
					titles: draftTalkPages
				});
			}
		}

		function selectNextDraft(r) {
			//console.log('in selectNextDraft');
			//console.log(r);
			if (r && r.query && r.query.pages) {
				var found = false;
				var skiplist = {}
				try {
					skiplist = JSON.parse(window.localStorage.getItem('draft-sort-burst-skiplist')) || {};
				} catch (e) {
					console.log('[draft-sort-burst]: error reading from localStorage cache');
					console.log(
						'\t' + e.name + ' message: ' + e.message +
						( e.at ? ' at: ' + e.at : '') +
						( e.text ? ' text: ' + e.text : '')
					);
				}
				$.each(r.query.pages, function(i,e) {
					if (parseInt(i) < 0) {
						var page = r.query.pages[i].title.replace(/^Draft talk:/, 'Draft:');
						if (page === mw.config.get('wgPageName').replace(/_/g, ' ')) {
							return true; // continue
						}
						if (skiplist[page]) {
							return true;
						}

						nextDraft = page;
						found = true;
						return false;
					}
				});
				//console.log('found:', found);
				if (!found) {
					//console.log('No suitable next draft found');
					query.cmcontinue = cmcontinue;
					postQuery();
					return;
				}

				$(document).on('draft_sort:saved', function() {
					window.location = '//en.wikipedia.org/wiki/' + nextDraft + '?draftsorttrigger=y';
				});

				$('#draft-sorter-wrapper .draft-sort-skip').click(function() {

					var currentPage = mw.config.get('wgPageName').replace(/_/g, ' ');
					try {
						var skiplist = JSON.parse(window.localStorage.getItem('draft-sort-burst-skiplist')) || {};
						skiplist[currentPage] = 1;
						window.localStorage.setItem('draft-sort-burst-skiplist', JSON.stringify(skiplist));
					}  catch(e) {}

					window.location = '//en.wikipedia.org/wiki/' + nextDraft + '?draftsorttrigger=y';
				});

			}
		}

		function postQuery() {
			//console.log(query);
			api.get(query)
				.then(checkTalkPages)
				.then(selectNextDraft)
				.fail(function(e) {
					console.log('API for getting next draft failed ' + e);
				});
		}

		postQuery();

	}

});

//</nowiki>