Open main menu

MediaWiki:Gadget-2020Cohort.js

Revision as of 18:19, 22 June 2020 by Jayprakash (talk | contribs) (Created page with "$( document ).ready( function (){ function init() { // Remove the default content $('#mw-content-text > p').remove(); $('#firstHeading').text('Create Fellow Page -...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
$( document ).ready( function (){

	function init() {
		// Remove the default content
		$('#mw-content-text > p').remove();
    	$('#firstHeading').text('Create Fellow Page - 2020');
    	
    	// Creating API Object
    	requestAPI = new mw.Api();
    	
    	catMemberParam = {
			"action": "query",
			"format": "json",
			"list": "categorymembers",
			"cmtitle": "Category:2020 cohort",
			"cmprop": "title",
			"cmtype": "page",
			"cmlimit": "500"
		};

		requestAPI.get( catMemberParam, { async: false }  ).done( function(resData){
			schoolOptions = [];
			members = resData.query.categorymembers;

			// Creating MenuItems array from Category Members
			members.forEach( function(mem){
				schoolOptions.push(
						new OO.ui.MenuOptionWidget( {
						data: mem.title,
						label: mem.title
					} )
				);
			});

			// Create widgets
			var bio = new OO.ui.MultilineTextInputWidget( {
	            	placeholder: 'Bio',
	            	autosize: true, 
	            	rows: 10
	        	} ),
	        	achievements = new OO.ui.MultilineTextInputWidget( {
	            	placeholder: 'Achievements',
	            	autosize: true, 
	            	rows: 10
	        	} ),
	        	social = new OO.ui.MultilineTextInputWidget( {
	            	placeholder: 'Social media profiles',
	            	autosize: true, 
	            	rows: 10
	        	} ),
		        name = new OO.ui.TextInputWidget( { 
		            placeholder: 'Name'
		        } ),
		        schoolAndcohort = new OO.ui.DropdownWidget( { 
		            label: 'Select school',
		            menu: {
						items: schoolOptions 
					}
		        } ),
		        major = new OO.ui.TextInputWidget( { 
		            placeholder: 'Majoring in'
		        } ),
		        country = new OO.ui.TextInputWidget( { 
		            placeholder: 'Country'
		        } ),
				createBtn = new OO.ui.ButtonWidget( { 
				    label: 'Create Page', 
				    flags: [ 'progressive', 'primary' ]
				} ),
				cancelBtn = new OO.ui.ButtonWidget( {
				    label: 'Cancel',
				    flags: [ 'primary', 'destructive' ],
				    href:  mw.config.get( 'wgServer' )
				} ),
				label2 = $('<p>').text('Name:').css('font-weight','bold' ),
				label3 = $('<p>').text('School (Cohort):').css('font-weight','bold' ),
				label4 = $('<p>').text('Majoring in:').css('font-weight','bold' ),
				label5 = $('<p>').text('Country:').css('font-weight','bold' ),
				label6 = $('<p>').text('Bio:').css('font-weight','bold' ),
				label7 = $('<p>').text('Achievements:').css('font-weight','bold' ),
				label8 = $('<p>').text('Social media profiles:').css('font-weight','bold' ),
				divMainBox = $('<div />').css( {
					'box-shadow': '0 .5rem 1rem rgba(0, 0, 0, .15)',
					'border': '1px solid',
					'padding': '1rem',
					'margin-bottom': '3rem',
					'border-radius': '.5rem'
				});

			divMainBox.append(
				label2, name.$element,
				label3, schoolAndcohort.$element,
				label4, major.$element,
				label5, country.$element, 
				label6, bio.$element,
				label7, achievements.$element,
				label8, social.$element,
				'<br/>',
				createBtn.$element,
				cancelBtn.$element
			);

			$( '#mw-content-text' ).append( divMainBox );

			// Event handler for Select cohort
			schoolAndcohortResp = '';
			schoolAndcohort.getMenu().on('select', function(data){
				schoolAndcohortResp = data.getData();
			});
			
			// Create button click event handler
			createBtn.on( 'click', function() {
				nameResp = name.getValue().trim(),
				majorResp = major.getValue().trim();
				countryResp = country.getValue().trim(),
				bioResp = bio.getValue().trim();
				achievementsResp = achievements.getValue().trim(),
				socialResp = social.getValue().trim();
	
				// Check whether the all fields are enough to run the function
				if( nameResp !== "" && schoolAndcohortResp !== "" 
					&& majorResp !== "" && countryResp !== "" ) {

					wikiContent = '{| class="wikitable" style="border: 5px ridge grey; float:right;" \n|-\n|';
					wikiContent += "[[File:Oalogo.jpg|300px]]\n|-\n|\n";
					wikiContent += ";Name: " + nameResp + "\n";
					wikiContent += ";School (Cohort): " + schoolAndcohortResp + "\n";
					wikiContent += ";Majoring in: " + majorResp + "\n";
					wikiContent += ";Country: " + countryResp + "\n";
					wikiContent += ";Email: [[Special:EmailUser/" + mw.config.get("wgUserName") + "]]\n";
					wikiContent += "|}\n";
					wikiContent += "==Bio==\n" + bioResp + "\n";
					wikiContent += "==Achievements==\n" + achievementsResp + "\n";
					wikiContent += "==Social media profiles==\n" + socialResp + "\n";
	
					pageTitle = "Fellow:" + nameResp;
					
					requestAPI.get( {
						formatversion: 2,
						action: 'query',
						titles: pageTitle,
						redirects: true
					}, { async: false } ).then( function ( response ) {
						var page = response.query.pages[ 0 ];
						if ( page.missing || page.invalid ) {
							doEdit( pageTitle, wikiContent );
						} else {
							requestAPI.get( {
								formatversion: 2,
								action: 'query',
								titles: pageTitle + " (" + /\d{4}/.exec( schoolAndcohortResp ) + ")",
								redirects: true
							}, { async: false } ).then( function ( response ) {
								var page = response.query.pages[ 0 ];
								if ( page.missing || page.invalid ) {
									doEdit( pageTitle + " (" + /\d{4}/.exec( schoolAndcohortResp ) + ")", wikiContent );
								} else {
									pageTitle = pageTitle + " (" + /(^.+)\(/.exec(a)[1].trim() + ", " + /\d{4}/.exec( schoolAndcohortResp ) + ")";
									doEdit( pageTitle, wikiContent );
								}
							});
						}
					} );
				} else {
					mw.notify( "Some fields have no text :( Please fill them." );
					return;
				}
	
	    	});
		}).fail( function(){
			$( '#mw-content-text' ).append( "Something went wront. Please report it to Jay Prakash (User:Jayprakash)." );
		});

    	function doEdit(title, wikiContent){

    		// Edit the page
			var editParams = {
				action: 'edit',
				title: title,
				text: wikiContent,
				summary: "Created Fellow Page - 2020",
				format: 'json'
			};
	
			requestAPI.postWithToken( 'csrf', editParams, { async: false } ).done( function ( res ) {
				if( res.edit.result === "Success"){
					mw.notify( title + " page has created :)");
					window.location.replace( mw.config.get( 'wgServer' ) + "/wiki/" + title );
				} else{
					mw.notify( "Something went worng :(" );
				}
			} );
    	}
	}
	
	if ( mw.config.get('wgCanonicalSpecialPageName') === 'Blankpage' && mw.config.get('wgTitle').split('/', 2)[1] === 'CreateFellow2020' ) {
		mw.loader.using( ['oojs-ui-core', 'oojs-ui-widgets', 'mediawiki.api', 'mediawiki.notify'], init );
	}
});