User:Mooeypoo/articlesandbox.js

var ARTICLE_REPO = mw.config.get( 'articlesandbox-article-repo' ) || '', NAME_FOR_SANDBOX = mw.config.get( 'articlesandbox-article-nameforsandbox' ) || 'sandbox', /**	 * Build the article structure from the API */	buildArticleStructure = function { var path, flatPath, articles = {};

if ( !ARTICLE_REPO ) { return $.Deferred.reject( 'noconfig' ); }

return ( new mw.Api ).get( {			action: 'query',			format: 'json',			list: 'prefixsearch',			pssearch: ARTICLE_REPO		} ) .then(			// Success			function ( queryData ) {				var articlesArr = queryData.query.prefixsearch;

articlesArr.forEach( function ( articleData ) {					var pieces = [],						title = articleData.title;

if ( title.indexOf( ARTICLE_REPO ) !== 0 ) { return; }					pieces = title.replace( ARTICLE_REPO, '' ).split( '/' ); pieces = pieces.filter( function ( piece ) {						return !!piece; // Get rid of empty strings					} );

// Build article structure path = articles; flatPath = ''; pieces.forEach( function ( piece ) {						flatPath += '/' + piece;

path[ piece ] = path[ piece ] || { _path: ARTICLE_REPO + flatPath, _articles: {} };						// Shift reference path = path[piece]._articles; } );				} );				if ( $.isEmptyObject( articles ) ) { return $.Deferred.reject( 'noarticles' ); }

return articles; },			// Convert failure to empty success function { return $.Deferred.reject( 'noarticles' ); }		);	},	// Language	messages = {		he: {			'articlesandbox-title': 'אשף ערכים',			'articlesandbox-button': 'אשף ערכים',			'articlesandbox-dismiss': 'ביטול',			'articlesandbox-goback': 'חזרה למסך הקודם',			'articlesandbox-create-article': ' ערך',			'articlesandbox-create-article-for': ' ערך עבור $1',			'articlesandbox-sections': 'רשימת ערכים',			'articlesandbox-create-button': ' ערך',			'articlesandbox-create-input-placeholder': 'כותרת הערך',			'articlesandbox-create-articlesummary': 'נוצר באמצעות |אשף הערכים'		},		en: {			'articlesandbox-title': 'Article helper',			'articlesandbox-button': 'Article helper',			'articlesandbox-dismiss': 'Dismiss',			'articlesandbox-goback': 'Go back',			'articlesandbox-title-error': 'Error displaying contents',			'articlesandbox-create-article': 'Create article',			'articlesandbox-create-article-for': 'Create article for $1', 'articlesandbox-sections': 'Available article templates', 'articlesandbox-create-button': 'Create article', 'articlesandbox-create-input-placeholder': 'Article title', 'articlesandbox-create-articlesummary': 'Created by |ArticleSandbox user script', 'articlesandbox-error-missing-repoconfig': 'Cannot load article templates, since there is no repository configured. Please configure a base repository for all article templates through setting the mw.config entry \'articlesandbox-article-repo\' where you load this script, and try again.', 'articlesandbox-error-missing-articles': 'Cannot find any defined article templates. Please add articles to the repository, and try again.', 'articlesandbox-error-missing-articles-gotorepo': 'Go to the article repository' }	};

// Set language, with default 'English' mw.messages.set(messages['en']); var lang = mw.config.get('wgUserLanguage'); if (lang && lang != 'en' && lang in messages) { mw.messages.set(messages[lang]); }

// Load the interface using the required module mw.loader.using( [ 'oojs-ui', 'mediawiki.api' ] ).then( function {	// Dialog settings; this must be inside the loader.using scope	// since it requires OOUI, and it must be on top to make sure	// the callers get its definition	var DialogPageLayout = function DialogPage( name, config ) {		DialogPageLayout.parent.apply( this, name, config );

if ( config.titleWidget ) { this.$element.append( config.titleWidget.$element ); }

if ( config.title ) { this.$element.append(				new OO.ui.LabelWidget( { label: config.title } )			);		}

if ( config.$content ) { this.$element.append( $content ); }	};	OO.inheritClass( DialogPageLayout, OO.ui.PageLayout ); /**	 * Article dialog *	 * @param {Object} [config] Configuration object */	var ArticleDialog = function ArticleDialog( config ) { ArticleDialog.parent.call( this, config ); this.chosenItem = null; this.error = false; };	OO.inheritClass( ArticleDialog, OO.ui.ProcessDialog ); ArticleDialog.static.actions = [ { label: mw.msg( 'articlesandbox-dismiss' ), modes: ['articles', 'error', 'create'], flags: 'safe' }, { action: 'back', label: mw.msg( 'articlesandbox-goback' ), modes: 'create', flags: 'safe', icon: 'arrowPrevious' } ];	ArticleDialog.static.title = mw.msg( 'articlesandbox-title' ); ArticleDialog.static.name = 'articlehelperdialog'; ArticleDialog.static.size = 'medium';

/**	 * Set error state for the dialog *	 * @param {string} [type='noarticles'] Error type; 'noconfig' or 'noarticles' */	ArticleDialog.prototype.setError = function ( type ) { var label = type === 'noconfig' ? mw.msg( 'articlesandbox-error-missing-repoconfig' ) : $( ' ' )				.append(					mw.msg( 'articlesandbox-error-missing-articles' ),					new OO.ui.ButtonWidget( { flags: [ 'progressive' ], icon: 'newWindow', label: mw.msg( 'articlesandbox-error-missing-articles-gotorepo' ), href: mw.config.get( 'wgArticlePath' ).replace( '$1', ARTICLE_REPO ), target: '_blank' } ).$element				);

this.error = true; this.errorLabel.setLabel( label ); this.showPage( 'error' ); };

/**	 * @inheritdoc */	ArticleDialog.prototype.initialize = function { var dialog = this; ArticleDialog.parent.prototype.initialize.apply( this, arguments ); // this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );

this.$articlesPage = $( ' ' ) .addClass( 'articlesandbox-page-articles' ) this.$createPageForm = $( ' ' ) .addClass( 'articlesandbox-page-create-form' );

this.errorLabel = new OO.ui.LabelWidget( {			classes: [ 'articlesandbox-error' ]		} ); this.createPageTitle = new OO.ui.LabelWidget( {			label: mw.msg( 'articlesandbox-create-article' ),			classes: [ 'articlesandbox-page-create-title' ]		} ),

this.bookletLayout = new OO.ui.BookletLayout; this.bookletLayout.addPages( [			new OO.ui.PageLayout( 'error', { title: mw.msg( 'articlesandbox-title-error' ), $content: this.errorLabel.$element } ),			new OO.ui.PageLayout( 'articles', { title: mw.msg( 'articlesandbox-create-article' ), $content: this.$articlesPage } ),			new OO.ui.PageLayout( 'create', { titleWidget: this.createPageTitle, $content: $( ' ' ) .addClass( 'articlesandbox-page-create' ) .append( this.$createPageForm ) } )		] );

this.$body.append( this.bookletLayout.$element ); };

/**	 * @inheritdoc */	ArticleDialog.prototype.getActionProcess = function ( action ) { if ( action === 'back' ) { this.showPage( 'articles' ); }		return ArticleDialog.parent.prototype.getActionProcess.call( this, action ); };

/**	 * @inheritdoc */	ArticleDialog.prototype.getSetupProcess = function ( data ) { return ArticleDialog.parent.prototype.getSetupProcess.call( this, data ) .next( function {				if ( this.error ) {					this.showPage( 'error' );				} else {					this.showPage( 'articles' );				}	        }, this ); };

/**	 * Build the 'create page' form. * This will be updated with details from the item as it is chosen *	 * @param {OO.ui.OptionWidget} item Chosen item */	ArticleDialog.prototype.buildCreatePageForm = function ( item ) { var data = item ? item.getData : {}, makeHiddenInput = function ( name, value ) { return $( ' ' ) .attr( 'type', 'hidden' ) .attr( 'name', name ) .attr( 'value', value ); },			// Mock a inputbox process $form = $( ' ' ) .attr( 'action', '/w/index.php' ) .attr( 'method', 'get' ) .attr( 'id', 'createbox' ) .attr( 'name', 'createbox' ) .append(					makeHiddenInput( 'veaction', 'edit' ),					makeHiddenInput( 'preload', data.path ),					makeHiddenInput( 'summary', mw.msg( 'articlesandbox-create-articlesummary' ) ),					makeHiddenInput( 'prefix', 'Special:MyPage/' + NAME_FOR_SANDBOX + '/')				); $form.append(			new OO.ui.TextInputWidget( { name: 'title', placeholder: mw.msg( 'articlesandbox-create-input-placeholder' ) } ).$element,			new OO.ui.ButtonInputWidget( { type: 'submit', icon: 'add', flags: [ 'progressive' ], label: mw.msg( 'articlesandbox-create-button' ), } ).$element		);

// Reset the page title label according to the chosen item this.createPageTitle.setLabel( mw.msg( 'articlesandbox-create-article-for', data.name ) );

// Reset the form and re-append it		this.$createPageForm.empty.append( $form ); };

/**	 * Show a specific page in the dialog *	 * @param {string} [name='articles'] Page name; 'articles', 'create' or 'error' */	ArticleDialog.prototype.showPage = function ( name ) { name = name || 'articles';

this.bookletLayout.setPage( name ); this.getActions.setMode( name ); };

/**	 * Respond to 'choose' event from any of the list widgets. *	 * @param {OO.ui.OptionWidget} item Chosen item */	ArticleDialog.prototype.onArticleListChoose = function ( item ) { var data = item.getData;

this.chosenItem = item;

if ( data.list ) { // Reset selection data.list.selectItem( null ); }

this.buildCreatePageForm( item ); this.showPage( 'create' ); };

/**	 * Create a list widget with articles from leaf nodes of the * article structure *	 * @param {Object} articles Article structure object */	ArticleDialog.prototype.createArticleListWidget = function ( articles ) { var listWidget = new OO.ui.SelectWidget( {				classes: [ 'articlesandbox-articles-section-list' ]			} ), pages = articles ? Object.keys( articles ) : [];

// Event listWidget.connect( this, { choose: 'onArticleListChoose' } );

// Add items from top layer pages.forEach( function ( page ) {			var items = [];			if ( $.isEmptyObject( articles[ page ]._articles ) ) {				// This is a leaf article, add item				items.push( new OO.ui.DecoratedOptionWidget( {					data: {						list: listWidget,						name: page,						path: articles[ page ]._path					},					icon: 'edit',					label: page				} ) );			} else {				// This is a category of sub pages, ignore that,				// it's being handled in #addArticleSection			}			listWidget.addItems( items );		} ); return listWidget; };

/**	 * Create a section for the article view from the article structure. * This takes the non-leaf nodes in the article structure, creates * a section and populates them with a listWidget that is full * of the subsequent leaf nodes, followed by any sub sections if * needed, recursively. *	 * @param {string} title Section title * @param {Object} articles Article structure object */	ArticleDialog.prototype.createArticlesSection = function ( title, articles ) { var dialog = this, listWidget = this.createArticleListWidget( articles ), pages = articles ? Object.keys( articles ) : [], titleWidget = new OO.ui.LabelWidget( {				classes: [ 'articlesandbox-articles-section-title' ],				label: title			} ), $section = $( ' ' ) .addClass( 'articlesandbox-articles-section' ) .append( titleWidget.$element, listWidget.$element );

// Look for sub sections pages.forEach( function ( page ) {			if ( !$.isEmptyObject( articles[ page ]._articles ) ) {				// This is another section, recurse				$section.append( dialog.createArticlesSection( page, articles[ page ]._articles ) );			}		} );		return $section; };

/**	 * Build the content based on the article structure given * 	 * @param {Object} articles Article structure with paths */	ArticleDialog.prototype.buildContent = function ( articles ) { var $articleSection = this.createArticlesSection(			mw.msg( 'articlesandbox-sections' ),			articles		); this.$articlesPage.append( $articleSection ); };

/**	 * @inheritdoc */	ArticleDialog.prototype.getBodyHeight = function { // 60% height // TODO: Figure out how to make the height variable // every time a page is switched return $( window ).height( true ) * 0.6; };

/** Create the interface **/

var mainDialog = new ArticleDialog, windowManager = new OO.ui.WindowManager, mainButton = new OO.ui.ButtonWidget( {			label: mw.msg( 'articlesandbox-button' ),			icon: 'article',			flags: [ 'progressive' ]		} );

mainButton.setDisabled( true ); windowManager.addWindows( [ mainDialog ] );

// Attach events mainButton.on( 'click', function {		windowManager.openWindow( mainDialog );	} );

if ( ARTICLE_REPO ) { // Get the data buildArticleStructure .then(				function ( articles ) {					mainDialog.buildContent( articles );				},				function ( errorType ) {					mainDialog.setError( errorType );				}			) .always( function {				mainButton.setDisabled( false );			} ); } else { // If ARTICLE_REPO is undefined, show an error mainDialog.setError( 'noconfig' ); mainButton.setDisabled( false ); }

// Load the stylesheet and wait for document ready to attach the // main button to the DOM $.when(		// Stylesheet		mw.loader.load( 'https://www.mediawiki.org/w/index.php?title=User:Mooeypoo/articlesandbox.css&action=raw&ctype=text/css', 'text/css' ),		// Document ready		$.ready	).then( function {		// Attach to DOM		$( '#right-navigation' ).append( mainButton.$element );		$( 'body' ).append( windowManager.$element );	} ); } );