Merge "MediaWikiServices: Don't assume, that old and new instances contains the same...
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.apisandbox.js
1 /*global OO */
2 ( function ( $, mw, OO ) {
3 'use strict';
4 var ApiSandbox, Util, WidgetMethods, Validators,
5 $content, panel, booklet, oldhash, windowManager, fullscreenButton,
6 api = new mw.Api(),
7 bookletPages = [],
8 availableFormats = {},
9 resultPage = null,
10 suppressErrors = true,
11 updatingBooklet = false,
12 pages = {},
13 moduleInfoCache = {};
14
15 WidgetMethods = {
16 textInputWidget: {
17 getApiValue: function () {
18 return this.getValue();
19 },
20 setApiValue: function ( v ) {
21 if ( v === undefined ) {
22 v = this.paramInfo[ 'default' ];
23 }
24 this.setValue( v );
25 },
26 apiCheckValid: function () {
27 var that = this;
28 return this.isValid().done( function ( ok ) {
29 ok = ok || suppressErrors;
30 that.setIcon( ok ? null : 'alert' );
31 that.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
32 } );
33 }
34 },
35
36 dateTimeInputWidget: {
37 isValid: function () {
38 var ok = !Util.apiBool( this.paramInfo.required ) || this.getApiValue() !== '';
39 return $.Deferred().resolve( ok ).promise();
40 }
41 },
42
43 tokenWidget: {
44 alertTokenError: function ( code, error ) {
45 windowManager.openWindow( 'errorAlert', {
46 title: mw.message(
47 'apisandbox-results-fixtoken-fail', this.paramInfo.tokentype
48 ).parse(),
49 message: error,
50 actions: [
51 {
52 action: 'accept',
53 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
54 flags: 'primary'
55 }
56 ]
57 } );
58 },
59 fetchToken: function () {
60 this.pushPending();
61 return api.getToken( this.paramInfo.tokentype )
62 .done( this.setApiValue.bind( this ) )
63 .fail( this.alertTokenError.bind( this ) )
64 .always( this.popPending.bind( this ) );
65 },
66 setApiValue: function ( v ) {
67 WidgetMethods.textInputWidget.setApiValue.call( this, v );
68 if ( v === '123ABC' ) {
69 this.fetchToken();
70 }
71 }
72 },
73
74 passwordWidget: {
75 getApiValueForDisplay: function () {
76 return '';
77 }
78 },
79
80 toggleSwitchWidget: {
81 getApiValue: function () {
82 return this.getValue() ? 1 : undefined;
83 },
84 setApiValue: function ( v ) {
85 this.setValue( Util.apiBool( v ) );
86 },
87 apiCheckValid: function () {
88 return $.Deferred().resolve( true ).promise();
89 }
90 },
91
92 dropdownWidget: {
93 getApiValue: function () {
94 var item = this.getMenu().getSelectedItem();
95 return item === null ? undefined : item.getData();
96 },
97 setApiValue: function ( v ) {
98 var menu = this.getMenu();
99
100 if ( v === undefined ) {
101 v = this.paramInfo[ 'default' ];
102 }
103 if ( v === undefined ) {
104 menu.selectItem();
105 } else {
106 menu.selectItemByData( String( v ) );
107 }
108 },
109 apiCheckValid: function () {
110 var ok = this.getApiValue() !== undefined || suppressErrors;
111 this.setIcon( ok ? null : 'alert' );
112 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
113 return $.Deferred().resolve( ok ).promise();
114 }
115 },
116
117 capsuleWidget: {
118 getApiValue: function () {
119 var items = this.getItemsData();
120 if ( items.join( '' ).indexOf( '|' ) === -1 ) {
121 return items.join( '|' );
122 } else {
123 return '\x1f' + items.join( '\x1f' );
124 }
125 },
126 setApiValue: function ( v ) {
127 if ( v === undefined || v === '' || v === '\x1f' ) {
128 this.setItemsFromData( [] );
129 } else {
130 v = String( v );
131 if ( v.indexOf( '\x1f' ) !== 0 ) {
132 this.setItemsFromData( v.split( '|' ) );
133 } else {
134 this.setItemsFromData( v.substr( 1 ).split( '\x1f' ) );
135 }
136 }
137 },
138 apiCheckValid: function () {
139 var ok = this.getApiValue() !== undefined || suppressErrors;
140 this.setIcon( ok ? null : 'alert' );
141 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
142 return $.Deferred().resolve( ok ).promise();
143 }
144 },
145
146 optionalWidget: {
147 getApiValue: function () {
148 return this.isDisabled() ? undefined : this.widget.getApiValue();
149 },
150 setApiValue: function ( v ) {
151 this.setDisabled( v === undefined );
152 this.widget.setApiValue( v );
153 },
154 apiCheckValid: function () {
155 if ( this.isDisabled() ) {
156 return $.Deferred().resolve( true ).promise();
157 } else {
158 return this.widget.apiCheckValid();
159 }
160 }
161 },
162
163 submoduleWidget: {
164 single: function () {
165 var v = this.isDisabled() ? this.paramInfo[ 'default' ] : this.getApiValue();
166 return v === undefined ? [] : [ { value: v, path: this.paramInfo.submodules[ v ] } ];
167 },
168 multi: function () {
169 var map = this.paramInfo.submodules,
170 v = this.isDisabled() ? this.paramInfo[ 'default' ] : this.getApiValue();
171 return v === undefined || v === '' ? [] : $.map( String( v ).split( '|' ), function ( v ) {
172 return { value: v, path: map[ v ] };
173 } );
174 }
175 },
176
177 uploadWidget: {
178 getApiValueForDisplay: function () {
179 return '...';
180 },
181 getApiValue: function () {
182 return this.getValue();
183 },
184 setApiValue: function () {
185 // Can't, sorry.
186 },
187 apiCheckValid: function () {
188 var ok = this.getValue() !== null || suppressErrors;
189 this.setIcon( ok ? null : 'alert' );
190 this.setIconTitle( ok ? '' : mw.message( 'apisandbox-alert-field' ).plain() );
191 return $.Deferred().resolve( ok ).promise();
192 }
193 }
194 };
195
196 Validators = {
197 generic: function () {
198 return !Util.apiBool( this.paramInfo.required ) || this.getApiValue() !== '';
199 }
200 };
201
202 /**
203 * @class mw.special.ApiSandbox.Utils
204 * @private
205 */
206 Util = {
207 /**
208 * Fetch API module info
209 *
210 * @param {string} module Module to fetch data for
211 * @return {jQuery.Promise}
212 */
213 fetchModuleInfo: function ( module ) {
214 var apiPromise,
215 deferred = $.Deferred();
216
217 if ( moduleInfoCache.hasOwnProperty( module ) ) {
218 return deferred
219 .resolve( moduleInfoCache[ module ] )
220 .promise( { abort: function () {} } );
221 } else {
222 apiPromise = api.post( {
223 action: 'paraminfo',
224 modules: module,
225 helpformat: 'html',
226 uselang: mw.config.get( 'wgUserLanguage' )
227 } ).done( function ( data ) {
228 var info;
229
230 if ( data.warnings && data.warnings.paraminfo ) {
231 deferred.reject( '???', data.warnings.paraminfo[ '*' ] );
232 return;
233 }
234
235 info = data.paraminfo.modules;
236 if ( !info || info.length !== 1 || info[ 0 ].path !== module ) {
237 deferred.reject( '???', 'No module data returned' );
238 return;
239 }
240
241 moduleInfoCache[ module ] = info[ 0 ];
242 deferred.resolve( info[ 0 ] );
243 } ).fail( function ( code, details ) {
244 if ( code === 'http' ) {
245 details = 'HTTP error: ' + details.exception;
246 } else if ( details.error ) {
247 details = details.error.info;
248 }
249 deferred.reject( code, details );
250 } );
251 return deferred
252 .promise( { abort: apiPromise.abort } );
253 }
254 },
255
256 /**
257 * Mark all currently-in-use tokens as bad
258 */
259 markTokensBad: function () {
260 var page, subpages, i,
261 checkPages = [ pages.main ];
262
263 while ( checkPages.length ) {
264 page = checkPages.shift();
265
266 if ( page.tokenWidget ) {
267 api.badToken( page.tokenWidget.paramInfo.tokentype );
268 }
269
270 subpages = page.getSubpages();
271 for ( i = 0; i < subpages.length; i++ ) {
272 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
273 checkPages.push( pages[ subpages[ i ].key ] );
274 }
275 }
276 }
277 },
278
279 /**
280 * Test an API boolean
281 *
282 * @param {Mixed} value
283 * @return {boolean}
284 */
285 apiBool: function ( value ) {
286 return value !== undefined && value !== false;
287 },
288
289 /**
290 * Create a widget for a parameter.
291 *
292 * @param {Object} pi Parameter info from API
293 * @param {Object} opts Additional options
294 * @return {OO.ui.Widget}
295 */
296 createWidgetForParameter: function ( pi, opts ) {
297 var widget, innerWidget, finalWidget, items, $button, $content, func,
298 multiMode = 'none';
299
300 opts = opts || {};
301
302 switch ( pi.type ) {
303 case 'boolean':
304 widget = new OO.ui.ToggleSwitchWidget();
305 widget.paramInfo = pi;
306 $.extend( widget, WidgetMethods.toggleSwitchWidget );
307 pi.required = true; // Avoid wrapping in the non-required widget
308 break;
309
310 case 'string':
311 case 'user':
312 if ( pi.tokentype ) {
313 widget = new TextInputWithIndicatorWidget( {
314 input: {
315 indicator: 'previous',
316 indicatorTitle: mw.message( 'apisandbox-fetch-token' ).text(),
317 required: Util.apiBool( pi.required )
318 }
319 } );
320 } else if ( Util.apiBool( pi.multi ) ) {
321 widget = new OO.ui.CapsuleMultiselectWidget( {
322 allowArbitrary: true
323 } );
324 widget.paramInfo = pi;
325 $.extend( widget, WidgetMethods.capsuleWidget );
326 } else {
327 widget = new OO.ui.TextInputWidget( {
328 required: Util.apiBool( pi.required )
329 } );
330 }
331 if ( !Util.apiBool( pi.multi ) ) {
332 widget.paramInfo = pi;
333 $.extend( widget, WidgetMethods.textInputWidget );
334 widget.setValidation( Validators.generic );
335 }
336 if ( pi.tokentype ) {
337 $.extend( widget, WidgetMethods.tokenWidget );
338 widget.input.paramInfo = pi;
339 $.extend( widget.input, WidgetMethods.textInputWidget );
340 $.extend( widget.input, WidgetMethods.tokenWidget );
341 widget.on( 'indicator', widget.fetchToken, [], widget );
342 }
343 break;
344
345 case 'text':
346 widget = new OO.ui.TextInputWidget( {
347 multiline: true,
348 required: Util.apiBool( pi.required )
349 } );
350 widget.paramInfo = pi;
351 $.extend( widget, WidgetMethods.textInputWidget );
352 widget.setValidation( Validators.generic );
353 break;
354
355 case 'password':
356 widget = new OO.ui.TextInputWidget( {
357 type: 'password',
358 required: Util.apiBool( pi.required )
359 } );
360 widget.paramInfo = pi;
361 $.extend( widget, WidgetMethods.textInputWidget );
362 $.extend( widget, WidgetMethods.passwordWidget );
363 widget.setValidation( Validators.generic );
364 multiMode = 'enter';
365 break;
366
367 case 'integer':
368 widget = new OO.ui.NumberInputWidget( {
369 required: Util.apiBool( pi.required ),
370 isInteger: true
371 } );
372 widget.setIcon = widget.input.setIcon.bind( widget.input );
373 widget.setIconTitle = widget.input.setIconTitle.bind( widget.input );
374 widget.isValid = widget.input.isValid.bind( widget.input );
375 widget.paramInfo = pi;
376 $.extend( widget, WidgetMethods.textInputWidget );
377 if ( Util.apiBool( pi.enforcerange ) ) {
378 widget.setRange( pi.min || -Infinity, pi.max || Infinity );
379 }
380 multiMode = 'enter';
381 break;
382
383 case 'limit':
384 widget = new OO.ui.NumberInputWidget( {
385 required: Util.apiBool( pi.required ),
386 isInteger: true
387 } );
388 widget.setIcon = widget.input.setIcon.bind( widget.input );
389 widget.setIconTitle = widget.input.setIconTitle.bind( widget.input );
390 widget.isValid = widget.input.isValid.bind( widget.input );
391 widget.input.setValidation( function ( value ) {
392 return value === 'max' || widget.validateNumber( value );
393 } );
394 widget.paramInfo = pi;
395 $.extend( widget, WidgetMethods.textInputWidget );
396 widget.setRange( pi.min || 0, mw.config.get( 'apihighlimits' ) ? pi.highmax : pi.max );
397 multiMode = 'enter';
398 break;
399
400 case 'timestamp':
401 widget = new mw.widgets.datetime.DateTimeInputWidget( {
402 formatter: {
403 format: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
404 },
405 required: Util.apiBool( pi.required ),
406 clearable: false
407 } );
408 widget.paramInfo = pi;
409 $.extend( widget, WidgetMethods.textInputWidget );
410 $.extend( widget, WidgetMethods.dateTimeInputWidget );
411 multiMode = 'indicator';
412 break;
413
414 case 'upload':
415 widget = new OO.ui.SelectFileWidget();
416 widget.paramInfo = pi;
417 $.extend( widget, WidgetMethods.uploadWidget );
418 break;
419
420 case 'namespace':
421 items = $.map( mw.config.get( 'wgFormattedNamespaces' ), function ( name, ns ) {
422 if ( ns === '0' ) {
423 name = mw.message( 'blanknamespace' ).text();
424 }
425 return new OO.ui.MenuOptionWidget( { data: ns, label: name } );
426 } ).sort( function ( a, b ) {
427 return a.data - b.data;
428 } );
429 if ( Util.apiBool( pi.multi ) ) {
430 widget = new OO.ui.CapsuleMultiselectWidget( {
431 menu: { items: items }
432 } );
433 widget.paramInfo = pi;
434 $.extend( widget, WidgetMethods.capsuleWidget );
435 } else {
436 widget = new OO.ui.DropdownWidget( {
437 menu: { items: items }
438 } );
439 widget.paramInfo = pi;
440 $.extend( widget, WidgetMethods.dropdownWidget );
441 }
442 break;
443
444 default:
445 if ( !$.isArray( pi.type ) ) {
446 throw new Error( 'Unknown parameter type ' + pi.type );
447 }
448
449 items = $.map( pi.type, function ( v ) {
450 return new OO.ui.MenuOptionWidget( { data: String( v ), label: String( v ) } );
451 } );
452 if ( Util.apiBool( pi.multi ) ) {
453 widget = new OO.ui.CapsuleMultiselectWidget( {
454 menu: { items: items }
455 } );
456 widget.paramInfo = pi;
457 $.extend( widget, WidgetMethods.capsuleWidget );
458 if ( Util.apiBool( pi.submodules ) ) {
459 widget.getSubmodules = WidgetMethods.submoduleWidget.multi;
460 widget.on( 'change', ApiSandbox.updateUI );
461 }
462 } else {
463 widget = new OO.ui.DropdownWidget( {
464 menu: { items: items }
465 } );
466 widget.paramInfo = pi;
467 $.extend( widget, WidgetMethods.dropdownWidget );
468 if ( Util.apiBool( pi.submodules ) ) {
469 widget.getSubmodules = WidgetMethods.submoduleWidget.single;
470 widget.getMenu().on( 'choose', ApiSandbox.updateUI );
471 }
472 }
473
474 break;
475 }
476
477 if ( Util.apiBool( pi.multi ) && multiMode !== 'none' ) {
478 innerWidget = widget;
479 switch ( multiMode ) {
480 case 'enter':
481 $content = innerWidget.$element;
482 break;
483
484 case 'indicator':
485 $button = innerWidget.$indicator;
486 $button.css( 'cursor', 'pointer' );
487 $button.attr( 'tabindex', 0 );
488 $button.parent().append( $button );
489 innerWidget.setIndicator( 'next' );
490 $content = innerWidget.$element;
491 break;
492
493 default:
494 throw new Error( 'Unknown multiMode "' + multiMode + '"' );
495 }
496
497 widget = new OO.ui.CapsuleMultiselectWidget( {
498 allowArbitrary: true,
499 popup: {
500 classes: [ 'mw-apisandbox-popup' ],
501 $content: $content
502 }
503 } );
504 widget.paramInfo = pi;
505 $.extend( widget, WidgetMethods.capsuleWidget );
506
507 func = function () {
508 if ( !innerWidget.isDisabled() ) {
509 innerWidget.apiCheckValid().done( function ( ok ) {
510 if ( ok ) {
511 widget.addItemsFromData( [ innerWidget.getApiValue() ] );
512 innerWidget.setApiValue( undefined );
513 }
514 } );
515 return false;
516 }
517 };
518 switch ( multiMode ) {
519 case 'enter':
520 innerWidget.connect( null, { enter: func } );
521 break;
522
523 case 'indicator':
524 $button.on( {
525 click: func,
526 keypress: function ( e ) {
527 if ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) {
528 func();
529 }
530 }
531 } );
532 break;
533 }
534 }
535
536 if ( Util.apiBool( pi.required ) || opts.nooptional ) {
537 finalWidget = widget;
538 } else {
539 finalWidget = new OptionalWidget( widget );
540 finalWidget.paramInfo = pi;
541 $.extend( finalWidget, WidgetMethods.optionalWidget );
542 if ( widget.getSubmodules ) {
543 finalWidget.getSubmodules = widget.getSubmodules.bind( widget );
544 finalWidget.on( 'disable', function () { setTimeout( ApiSandbox.updateUI ); } );
545 }
546 finalWidget.setDisabled( true );
547 }
548
549 widget.setApiValue( pi[ 'default' ] );
550
551 return finalWidget;
552 },
553
554 /**
555 * Parse an HTML string, adding target="_blank" to any links
556 *
557 * @param {string} html HTML to parse
558 * @return {jQuery}
559 */
560 parseHTML: function ( html ) {
561 var $ret = $( $.parseHTML( html ) );
562 $ret.filter( 'a' ).add( $ret.find( 'a' ) )
563 .filter( '[href]:not([target])' )
564 .attr( 'target', '_blank' );
565 return $ret;
566 }
567 };
568
569 /**
570 * Interface to ApiSandbox UI
571 *
572 * @class mw.special.ApiSandbox
573 */
574 ApiSandbox = {
575 /**
576 * Initialize the UI
577 *
578 * Automatically called on $.ready()
579 */
580 init: function () {
581 var $toolbar;
582
583 $content = $( '#mw-apisandbox' );
584
585 windowManager = new OO.ui.WindowManager();
586 $( 'body' ).append( windowManager.$element );
587 windowManager.addWindows( {
588 errorAlert: new OO.ui.MessageDialog()
589 } );
590
591 fullscreenButton = new OO.ui.ButtonWidget( {
592 label: mw.message( 'apisandbox-fullscreen' ).text(),
593 title: mw.message( 'apisandbox-fullscreen-tooltip' ).text()
594 } ).on( 'click', ApiSandbox.toggleFullscreen );
595
596 $toolbar = $( '<div>' )
597 .addClass( 'mw-apisandbox-toolbar' )
598 .append(
599 fullscreenButton.$element,
600 new OO.ui.ButtonWidget( {
601 label: mw.message( 'apisandbox-submit' ).text(),
602 flags: [ 'primary', 'constructive' ]
603 } ).on( 'click', ApiSandbox.sendRequest ).$element,
604 new OO.ui.ButtonWidget( {
605 label: mw.message( 'apisandbox-reset' ).text(),
606 flags: 'destructive'
607 } ).on( 'click', ApiSandbox.resetUI ).$element
608 );
609
610 booklet = new OO.ui.BookletLayout( {
611 outlined: true,
612 autoFocus: false
613 } );
614
615 panel = new OO.ui.PanelLayout( {
616 classes: [ 'mw-apisandbox-container' ],
617 content: [ booklet ],
618 expanded: false,
619 framed: true
620 } );
621
622 pages.main = new ApiSandbox.PageLayout( { key: 'main', path: 'main' } );
623
624 // Parse the current hash string
625 if ( !ApiSandbox.loadFromHash() ) {
626 ApiSandbox.updateUI();
627 }
628
629 // If the hashchange event exists, use it. Otherwise, fake it.
630 // And, of course, IE has to be dumb.
631 if ( 'onhashchange' in window &&
632 ( document.documentMode === undefined || document.documentMode >= 8 )
633 ) {
634 $( window ).on( 'hashchange', ApiSandbox.loadFromHash );
635 } else {
636 setInterval( function () {
637 if ( oldhash !== location.hash ) {
638 ApiSandbox.loadFromHash();
639 }
640 }, 1000 );
641 }
642
643 $content
644 .empty()
645 .append( $( '<p>' ).append( mw.message( 'apisandbox-intro' ).parse() ) )
646 .append(
647 $( '<div>', { id: 'mw-apisandbox-ui' } )
648 .append( $toolbar )
649 .append( panel.$element )
650 );
651
652 $( window ).on( 'resize', ApiSandbox.resizePanel );
653
654 ApiSandbox.resizePanel();
655 },
656
657 /**
658 * Toggle "fullscreen" mode
659 */
660 toggleFullscreen: function () {
661 var $body = $( document.body );
662
663 $body.toggleClass( 'mw-apisandbox-fullscreen' );
664 if ( $body.hasClass( 'mw-apisandbox-fullscreen' ) ) {
665 fullscreenButton.setLabel( mw.message( 'apisandbox-unfullscreen' ).text() );
666 fullscreenButton.setTitle( mw.message( 'apisandbox-unfullscreen-tooltip' ).text() );
667 $body.append( $( '#mw-apisandbox-ui' ) );
668 } else {
669 fullscreenButton.setLabel( mw.message( 'apisandbox-fullscreen' ).text() );
670 fullscreenButton.setTitle( mw.message( 'apisandbox-fullscreen-tooltip' ).text() );
671 $content.append( $( '#mw-apisandbox-ui' ) );
672 }
673 ApiSandbox.resizePanel();
674 },
675
676 /**
677 * Set the height of the panel based on the current viewport.
678 */
679 resizePanel: function () {
680 var height = $( window ).height(),
681 contentTop = $content.offset().top;
682
683 if ( $( document.body ).hasClass( 'mw-apisandbox-fullscreen' ) ) {
684 height -= panel.$element.offset().top - $( '#mw-apisandbox-ui' ).offset().top;
685 panel.$element.height( height - 1 );
686 } else {
687 // Subtract the height of the intro text
688 height -= panel.$element.offset().top - contentTop;
689
690 panel.$element.height( height - 10 );
691 $( window ).scrollTop( contentTop - 5 );
692 }
693 },
694
695 /**
696 * Update the current query when the page hash changes
697 */
698 loadFromHash: function () {
699 var params, m, re,
700 hash = location.hash;
701
702 if ( oldhash === hash ) {
703 return false;
704 }
705 oldhash = hash;
706 if ( hash === '' ) {
707 return false;
708 }
709
710 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
711 params = {};
712 hash = hash.replace( /\+/g, '%20' );
713 re = /([^&=#]+)=?([^&#]*)/g;
714 while ( ( m = re.exec( hash ) ) ) {
715 params[ decodeURIComponent( m[ 1 ] ) ] = decodeURIComponent( m[ 2 ] );
716 }
717
718 ApiSandbox.updateUI( params );
719 return true;
720 },
721
722 /**
723 * Update the pages in the booklet
724 *
725 * @param {Object} [params] Optional query parameters to load
726 */
727 updateUI: function ( params ) {
728 var i, page, subpages, j, removePages,
729 addPages = [];
730
731 if ( !$.isPlainObject( params ) ) {
732 params = undefined;
733 }
734
735 if ( updatingBooklet ) {
736 return;
737 }
738 updatingBooklet = true;
739 try {
740 if ( params !== undefined ) {
741 pages.main.loadQueryParams( params );
742 }
743 addPages.push( pages.main );
744 if ( resultPage !== null ) {
745 addPages.push( resultPage );
746 }
747 pages.main.apiCheckValid();
748
749 i = 0;
750 while ( addPages.length ) {
751 page = addPages.shift();
752 if ( bookletPages[ i ] !== page ) {
753 for ( j = i; j < bookletPages.length; j++ ) {
754 if ( bookletPages[ j ].getName() === page.getName() ) {
755 bookletPages.splice( j, 1 );
756 }
757 }
758 bookletPages.splice( i, 0, page );
759 booklet.addPages( [ page ], i );
760 }
761 i++;
762
763 if ( page.getSubpages ) {
764 subpages = page.getSubpages();
765 for ( j = 0; j < subpages.length; j++ ) {
766 if ( !pages.hasOwnProperty( subpages[ j ].key ) ) {
767 subpages[ j ].indentLevel = page.indentLevel + 1;
768 pages[ subpages[ j ].key ] = new ApiSandbox.PageLayout( subpages[ j ] );
769 }
770 if ( params !== undefined ) {
771 pages[ subpages[ j ].key ].loadQueryParams( params );
772 }
773 addPages.splice( j, 0, pages[ subpages[ j ].key ] );
774 pages[ subpages[ j ].key ].apiCheckValid();
775 }
776 }
777 }
778
779 if ( bookletPages.length > i ) {
780 removePages = bookletPages.splice( i, bookletPages.length - i );
781 booklet.removePages( removePages );
782 }
783
784 if ( !booklet.getCurrentPageName() ) {
785 booklet.selectFirstSelectablePage();
786 }
787 } finally {
788 updatingBooklet = false;
789 }
790 },
791
792 /**
793 * Reset button handler
794 */
795 resetUI: function () {
796 suppressErrors = true;
797 pages = {
798 main: new ApiSandbox.PageLayout( { key: 'main', path: 'main' } )
799 };
800 resultPage = null;
801 ApiSandbox.updateUI();
802 },
803
804 /**
805 * Submit button handler
806 */
807 sendRequest: function () {
808 var page, subpages, i, query, $result, $focus,
809 progress, $progressText, progressLoading,
810 deferreds = [],
811 params = {},
812 displayParams = {},
813 checkPages = [ pages.main ];
814
815 // Blur any focused widget before submit, because
816 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
817 $focus = $( '#mw-apisandbox-ui' ).find( document.activeElement );
818 if ( $focus.length ) {
819 $focus[ 0 ].blur();
820 }
821
822 suppressErrors = false;
823
824 while ( checkPages.length ) {
825 page = checkPages.shift();
826 deferreds.push( page.apiCheckValid() );
827 page.getQueryParams( params, displayParams );
828 subpages = page.getSubpages();
829 for ( i = 0; i < subpages.length; i++ ) {
830 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
831 checkPages.push( pages[ subpages[ i ].key ] );
832 }
833 }
834 }
835
836 $.when.apply( $, deferreds ).done( function () {
837 if ( $.inArray( false, arguments ) !== -1 ) {
838 windowManager.openWindow( 'errorAlert', {
839 title: mw.message( 'apisandbox-submit-invalid-fields-title' ).parse(),
840 message: mw.message( 'apisandbox-submit-invalid-fields-message' ).parse(),
841 actions: [
842 {
843 action: 'accept',
844 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
845 flags: 'primary'
846 }
847 ]
848 } );
849 return;
850 }
851
852 query = $.param( displayParams );
853
854 // Force a 'fm' format with wrappedhtml=1, if available
855 if ( params.format !== undefined ) {
856 if ( availableFormats.hasOwnProperty( params.format + 'fm' ) ) {
857 params.format = params.format + 'fm';
858 }
859 if ( params.format.substr( -2 ) === 'fm' ) {
860 params.wrappedhtml = 1;
861 }
862 }
863
864 progressLoading = false;
865 $progressText = $( '<span>' ).text( mw.message( 'apisandbox-sending-request' ).text() );
866 progress = new OO.ui.ProgressBarWidget( {
867 progress: false,
868 $content: $progressText
869 } );
870
871 $result = $( '<div>' )
872 .append( progress.$element );
873
874 resultPage = page = new OO.ui.PageLayout( '|results|' );
875 page.setupOutlineItem = function () {
876 this.outlineItem.setLabel( mw.message( 'apisandbox-results' ).text() );
877 };
878 page.$element.empty()
879 .append(
880 new OO.ui.FieldLayout(
881 new OO.ui.TextInputWidget( {
882 readOnly: true,
883 value: mw.util.wikiScript( 'api' ) + '?' + query
884 } ), {
885 label: mw.message( 'apisandbox-request-url-label' ).parse()
886 }
887 ).$element,
888 $result
889 );
890 ApiSandbox.updateUI();
891 booklet.setPage( '|results|' );
892
893 location.href = oldhash = '#' + query;
894
895 api.post( params, {
896 contentType: 'multipart/form-data',
897 dataType: 'text',
898 xhr: function () {
899 var xhr = new window.XMLHttpRequest();
900 xhr.upload.addEventListener( 'progress', function ( e ) {
901 if ( !progressLoading ) {
902 if ( e.lengthComputable ) {
903 progress.setProgress( e.loaded * 100 / e.total );
904 } else {
905 progress.setProgress( false );
906 }
907 }
908 } );
909 xhr.addEventListener( 'progress', function ( e ) {
910 if ( !progressLoading ) {
911 progressLoading = true;
912 $progressText.text( mw.message( 'apisandbox-loading-results' ).text() );
913 }
914 if ( e.lengthComputable ) {
915 progress.setProgress( e.loaded * 100 / e.total );
916 } else {
917 progress.setProgress( false );
918 }
919 } );
920 return xhr;
921 }
922 } )
923 .then( null, function ( code, data, result, jqXHR ) {
924 if ( code !== 'http' ) {
925 // Not really an error, work around mw.Api thinking it is.
926 return $.Deferred()
927 .resolve( result, jqXHR )
928 .promise();
929 }
930 return this;
931 } )
932 .fail( function ( code, data ) {
933 var details = 'HTTP error: ' + data.exception;
934 $result.empty()
935 .append(
936 new OO.ui.LabelWidget( {
937 label: mw.message( 'apisandbox-results-error', details ).text(),
938 classes: [ 'error' ]
939 } ).$element
940 );
941 } )
942 .done( function ( data, jqXHR ) {
943 var m, loadTime, button,
944 ct = jqXHR.getResponseHeader( 'Content-Type' );
945
946 $result.empty();
947 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct ) ) {
948 data = $.parseJSON( data );
949 if ( data.modules.length ) {
950 mw.loader.load( data.modules );
951 }
952 $result.append( Util.parseHTML( data.html ) );
953 loadTime = data.time;
954 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
955 $result.append( Util.parseHTML( m[ 0 ] ) );
956 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
957 loadTime = parseInt( m[ 1 ], 10 );
958 }
959 } else {
960 $( '<pre>' )
961 .addClass( 'api-pretty-content' )
962 .text( data )
963 .appendTo( $result );
964 }
965 if ( typeof loadTime === 'number' ) {
966 $result.append(
967 $( '<div>' ).append(
968 new OO.ui.LabelWidget( {
969 label: mw.message( 'apisandbox-request-time', loadTime ).text()
970 } ).$element
971 )
972 );
973 }
974
975 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
976 // Flush all saved tokens in case one of them is the bad one.
977 Util.markTokensBad();
978 button = new OO.ui.ButtonWidget( {
979 label: mw.message( 'apisandbox-results-fixtoken' ).text()
980 } );
981 button.on( 'click', ApiSandbox.fixTokenAndResend )
982 .on( 'click', button.setDisabled, [ true ], button )
983 .$element.appendTo( $result );
984 }
985 } );
986 } );
987 },
988
989 /**
990 * Handler for the "Correct token and resubmit" button
991 *
992 * Used on a 'badtoken' error, it re-fetches token parameters for all
993 * pages and then re-submits the query.
994 */
995 fixTokenAndResend: function () {
996 var page, subpages, i, k,
997 ok = true,
998 tokenWait = { dummy: true },
999 checkPages = [ pages.main ],
1000 success = function ( k ) {
1001 delete tokenWait[ k ];
1002 if ( ok && $.isEmptyObject( tokenWait ) ) {
1003 ApiSandbox.sendRequest();
1004 }
1005 },
1006 failure = function ( k ) {
1007 delete tokenWait[ k ];
1008 ok = false;
1009 };
1010
1011 while ( checkPages.length ) {
1012 page = checkPages.shift();
1013
1014 if ( page.tokenWidget ) {
1015 k = page.apiModule + page.tokenWidget.paramInfo.name;
1016 tokenWait[ k ] = page.tokenWidget.fetchToken()
1017 .done( success.bind( page.tokenWidget, k ) )
1018 .fail( failure.bind( page.tokenWidget, k ) );
1019 }
1020
1021 subpages = page.getSubpages();
1022 for ( i = 0; i < subpages.length; i++ ) {
1023 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1024 checkPages.push( pages[ subpages[ i ].key ] );
1025 }
1026 }
1027 }
1028
1029 success( 'dummy', '' );
1030 },
1031
1032 /**
1033 * Reset validity indicators for all widgets
1034 */
1035 updateValidityIndicators: function () {
1036 var page, subpages, i,
1037 checkPages = [ pages.main ];
1038
1039 while ( checkPages.length ) {
1040 page = checkPages.shift();
1041 page.apiCheckValid();
1042 subpages = page.getSubpages();
1043 for ( i = 0; i < subpages.length; i++ ) {
1044 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1045 checkPages.push( pages[ subpages[ i ].key ] );
1046 }
1047 }
1048 }
1049 }
1050 };
1051
1052 /**
1053 * PageLayout for API modules
1054 *
1055 * @class
1056 * @private
1057 * @extends OO.ui.PageLayout
1058 * @constructor
1059 * @param {Object} [config] Configuration options
1060 */
1061 ApiSandbox.PageLayout = function ( config ) {
1062 config = $.extend( { prefix: '' }, config );
1063 this.displayText = config.key;
1064 this.apiModule = config.path;
1065 this.prefix = config.prefix;
1066 this.paramInfo = null;
1067 this.apiIsValid = true;
1068 this.loadFromQueryParams = null;
1069 this.widgets = {};
1070 this.tokenWidget = null;
1071 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1072 ApiSandbox.PageLayout[ 'super' ].call( this, config.key, config );
1073 this.loadParamInfo();
1074 };
1075 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1076 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1077 this.outlineItem.setLevel( this.indentLevel );
1078 this.outlineItem.setLabel( this.displayText );
1079 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1080 this.outlineItem.setIconTitle(
1081 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1082 );
1083 };
1084
1085 /**
1086 * Fetch module information for this page's module, then create UI
1087 */
1088 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1089 var dynamicFieldset, dynamicParamNameWidget,
1090 that = this,
1091 removeDynamicParamWidget = function ( name, layout ) {
1092 dynamicFieldset.removeItems( [ layout ] );
1093 delete that.widgets[ name ];
1094 },
1095 addDynamicParamWidget = function () {
1096 var name, layout, widget, button;
1097
1098 // Check name is filled in
1099 name = dynamicParamNameWidget.getValue().trim();
1100 if ( name === '' ) {
1101 dynamicParamNameWidget.focus();
1102 return;
1103 }
1104
1105 if ( that.widgets[ name ] !== undefined ) {
1106 windowManager.openWindow( 'errorAlert', {
1107 title: mw.message(
1108 'apisandbox-dynamic-error-exists', name
1109 ).parse(),
1110 actions: [
1111 {
1112 action: 'accept',
1113 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1114 flags: 'primary'
1115 }
1116 ]
1117 } );
1118 return;
1119 }
1120
1121 widget = Util.createWidgetForParameter( {
1122 name: name,
1123 type: 'string',
1124 'default': ''
1125 }, {
1126 nooptional: true
1127 } );
1128 button = new OO.ui.ButtonWidget( {
1129 icon: 'remove',
1130 flags: 'destructive'
1131 } );
1132 layout = new OO.ui.ActionFieldLayout(
1133 widget,
1134 button,
1135 {
1136 label: name,
1137 align: 'left'
1138 }
1139 );
1140 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1141 that.widgets[ name ] = widget;
1142 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1143 widget.focus();
1144
1145 dynamicParamNameWidget.setValue( '' );
1146 };
1147
1148 this.$element.empty()
1149 .append( new OO.ui.ProgressBarWidget( {
1150 progress: false,
1151 text: mw.message( 'apisandbox-loading', this.displayText ).text()
1152 } ).$element );
1153
1154 Util.fetchModuleInfo( this.apiModule )
1155 .done( function ( pi ) {
1156 var prefix, i, j, dl, widget, $widgetLabel, widgetField, helpField, tmp, flag, count,
1157 items = [],
1158 deprecatedItems = [],
1159 buttons = [],
1160 filterFmModules = function ( v ) {
1161 return v.substr( -2 ) !== 'fm' ||
1162 !availableFormats.hasOwnProperty( v.substr( 0, v.length - 2 ) );
1163 },
1164 widgetLabelOnClick = function () {
1165 var f = this.getField();
1166 if ( $.isFunction( f.setDisabled ) ) {
1167 f.setDisabled( false );
1168 }
1169 if ( $.isFunction( f.focus ) ) {
1170 f.focus();
1171 }
1172 },
1173 doNothing = function () {};
1174
1175 // This is something of a hack. We always want the 'format' and
1176 // 'action' parameters from the main module to be specified,
1177 // and for 'format' we also want to simplify the dropdown since
1178 // we always send the 'fm' variant.
1179 if ( that.apiModule === 'main' ) {
1180 for ( i = 0; i < pi.parameters.length; i++ ) {
1181 if ( pi.parameters[ i ].name === 'action' ) {
1182 pi.parameters[ i ].required = true;
1183 delete pi.parameters[ i ][ 'default' ];
1184 }
1185 if ( pi.parameters[ i ].name === 'format' ) {
1186 tmp = pi.parameters[ i ].type;
1187 for ( j = 0; j < tmp.length; j++ ) {
1188 availableFormats[ tmp[ j ] ] = true;
1189 }
1190 pi.parameters[ i ].type = $.grep( tmp, filterFmModules );
1191 pi.parameters[ i ][ 'default' ] = 'json';
1192 pi.parameters[ i ].required = true;
1193 }
1194 }
1195 }
1196
1197 // Hide the 'wrappedhtml' parameter on format modules
1198 if ( pi.group === 'format' ) {
1199 pi.parameters = $.grep( pi.parameters, function ( p ) {
1200 return p.name !== 'wrappedhtml';
1201 } );
1202 }
1203
1204 that.paramInfo = pi;
1205
1206 items.push( new OO.ui.FieldLayout(
1207 new OO.ui.Widget( {} ).toggle( false ), {
1208 align: 'top',
1209 label: Util.parseHTML( pi.description )
1210 }
1211 ) );
1212
1213 if ( pi.helpurls.length ) {
1214 buttons.push( new OO.ui.PopupButtonWidget( {
1215 label: mw.message( 'apisandbox-helpurls' ).text(),
1216 icon: 'help',
1217 popup: {
1218 $content: $( '<ul>' ).append( $.map( pi.helpurls, function ( link ) {
1219 return $( '<li>' ).append( $( '<a>', {
1220 href: link,
1221 target: '_blank',
1222 text: link
1223 } ) );
1224 } ) )
1225 }
1226 } ) );
1227 }
1228
1229 if ( pi.examples.length ) {
1230 buttons.push( new OO.ui.PopupButtonWidget( {
1231 label: mw.message( 'apisandbox-examples' ).text(),
1232 icon: 'code',
1233 popup: {
1234 $content: $( '<ul>' ).append( $.map( pi.examples, function ( example ) {
1235 var a = $( '<a>', {
1236 href: '#' + example.query,
1237 html: example.description
1238 } );
1239 a.find( 'a' ).contents().unwrap(); // Can't nest links
1240 return $( '<li>' ).append( a );
1241 } ) )
1242 }
1243 } ) );
1244 }
1245
1246 if ( buttons.length ) {
1247 items.push( new OO.ui.FieldLayout(
1248 new OO.ui.ButtonGroupWidget( {
1249 items: buttons
1250 } ), { align: 'top' }
1251 ) );
1252 }
1253
1254 if ( pi.parameters.length ) {
1255 prefix = that.prefix + pi.prefix;
1256 for ( i = 0; i < pi.parameters.length; i++ ) {
1257 widget = Util.createWidgetForParameter( pi.parameters[ i ] );
1258 that.widgets[ prefix + pi.parameters[ i ].name ] = widget;
1259 if ( pi.parameters[ i ].tokentype ) {
1260 that.tokenWidget = widget;
1261 }
1262
1263 dl = $( '<dl>' );
1264 dl.append( $( '<dd>', {
1265 addClass: 'description',
1266 append: Util.parseHTML( pi.parameters[ i ].description )
1267 } ) );
1268 if ( pi.parameters[ i ].info && pi.parameters[ i ].info.length ) {
1269 for ( j = 0; j < pi.parameters[ i ].info.length; j++ ) {
1270 dl.append( $( '<dd>', {
1271 addClass: 'info',
1272 append: Util.parseHTML( pi.parameters[ i ].info[ j ] )
1273 } ) );
1274 }
1275 }
1276 flag = true;
1277 count = 1e100;
1278 switch ( pi.parameters[ i ].type ) {
1279 case 'namespace':
1280 flag = false;
1281 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1282 break;
1283
1284 case 'limit':
1285 if ( pi.parameters[ i ].highmax !== undefined ) {
1286 dl.append( $( '<dd>', {
1287 addClass: 'info',
1288 append: Util.parseHTML( mw.message(
1289 'api-help-param-limit2', pi.parameters[ i ].max, pi.parameters[ i ].highmax
1290 ).parse() )
1291 } ) );
1292 } else {
1293 dl.append( $( '<dd>', {
1294 addClass: 'info',
1295 append: Util.parseHTML( mw.message(
1296 'api-help-param-limit', pi.parameters[ i ].max
1297 ).parse() )
1298 } ) );
1299 }
1300 break;
1301
1302 case 'integer':
1303 tmp = '';
1304 if ( pi.parameters[ i ].min !== undefined ) {
1305 tmp += 'min';
1306 }
1307 if ( pi.parameters[ i ].max !== undefined ) {
1308 tmp += 'max';
1309 }
1310 if ( tmp !== '' ) {
1311 dl.append( $( '<dd>', {
1312 addClass: 'info',
1313 append: Util.parseHTML( mw.message(
1314 'api-help-param-integer-' + tmp,
1315 Util.apiBool( pi.parameters[ i ].multi ) ? 2 : 1,
1316 pi.parameters[ i ].min, pi.parameters[ i ].max
1317 ).parse() )
1318 } ) );
1319 }
1320 break;
1321
1322 default:
1323 if ( $.isArray( pi.parameters[ i ].type ) ) {
1324 flag = false;
1325 count = pi.parameters[ i ].type.length;
1326 }
1327 break;
1328 }
1329 if ( Util.apiBool( pi.parameters[ i ].multi ) ) {
1330 tmp = [];
1331 if ( flag && !( widget instanceof OO.ui.CapsuleMultiselectWidget ) &&
1332 !(
1333 widget instanceof OptionalWidget &&
1334 widget.widget instanceof OO.ui.CapsuleMultiselectWidget
1335 )
1336 ) {
1337 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1338 }
1339 if ( count > pi.parameters[ i ].lowlimit ) {
1340 tmp.push(
1341 mw.message( 'api-help-param-multi-max',
1342 pi.parameters[ i ].lowlimit, pi.parameters[ i ].highlimit
1343 ).parse()
1344 );
1345 }
1346 if ( tmp.length ) {
1347 dl.append( $( '<dd>', {
1348 addClass: 'info',
1349 append: Util.parseHTML( tmp.join( ' ' ) )
1350 } ) );
1351 }
1352 }
1353 helpField = new OO.ui.FieldLayout(
1354 new OO.ui.Widget( {
1355 $content: '\xa0',
1356 classes: [ 'mw-apisandbox-spacer' ]
1357 } ), {
1358 align: 'inline',
1359 classes: [ 'mw-apisandbox-help-field' ],
1360 label: dl
1361 }
1362 );
1363
1364 $widgetLabel = $( '<span>' );
1365 widgetField = new OO.ui.FieldLayout(
1366 widget,
1367 {
1368 align: 'left',
1369 classes: [ 'mw-apisandbox-widget-field' ],
1370 label: prefix + pi.parameters[ i ].name,
1371 $label: $widgetLabel
1372 }
1373 );
1374
1375 // FieldLayout only does click for InputElement
1376 // widgets. So supply our own click handler.
1377 $widgetLabel.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1378
1379 // Don't grey out the label when the field is disabled,
1380 // it makes it too hard to read and our "disabled"
1381 // isn't really disabled.
1382 widgetField.onFieldDisable = doNothing;
1383
1384 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1385 deprecatedItems.push( widgetField, helpField );
1386 } else {
1387 items.push( widgetField, helpField );
1388 }
1389 }
1390 }
1391
1392 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1393 items.push( new OO.ui.FieldLayout(
1394 new OO.ui.Widget( {} ).toggle( false ), {
1395 align: 'top',
1396 label: Util.parseHTML( mw.message( 'apisandbox-no-parameters' ).parse() )
1397 }
1398 ) );
1399 }
1400
1401 that.$element.empty();
1402
1403 new OO.ui.FieldsetLayout( {
1404 label: that.displayText
1405 } ).addItems( items )
1406 .$element.appendTo( that.$element );
1407
1408 if ( Util.apiBool( pi.dynamicparameters ) ) {
1409 dynamicFieldset = new OO.ui.FieldsetLayout();
1410 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1411 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1412 } ).on( 'enter', addDynamicParamWidget );
1413 dynamicFieldset.addItems( [
1414 new OO.ui.FieldLayout(
1415 new OO.ui.Widget( {} ).toggle( false ), {
1416 align: 'top',
1417 label: Util.parseHTML( pi.dynamicparameters )
1418 }
1419 ),
1420 new OO.ui.ActionFieldLayout(
1421 dynamicParamNameWidget,
1422 new OO.ui.ButtonWidget( {
1423 icon: 'add',
1424 flags: 'constructive'
1425 } ).on( 'click', addDynamicParamWidget ),
1426 {
1427 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1428 align: 'left'
1429 }
1430 )
1431 ] );
1432 $( '<fieldset>' )
1433 .append(
1434 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1435 dynamicFieldset.$element
1436 )
1437 .appendTo( that.$element );
1438 }
1439
1440 if ( deprecatedItems.length ) {
1441 tmp = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1442 $( '<fieldset>' )
1443 .append(
1444 $( '<legend>' ).append(
1445 new OO.ui.ToggleButtonWidget( {
1446 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1447 } ).on( 'change', tmp.toggle, [], tmp ).$element
1448 ),
1449 tmp.$element
1450 )
1451 .appendTo( that.$element );
1452 }
1453
1454 // Load stored params, if any, then update the booklet if we
1455 // have subpages (or else just update our valid-indicator).
1456 tmp = that.loadFromQueryParams;
1457 that.loadFromQueryParams = null;
1458 if ( $.isPlainObject( tmp ) ) {
1459 that.loadQueryParams( tmp );
1460 }
1461 if ( that.getSubpages().length > 0 ) {
1462 ApiSandbox.updateUI( tmp );
1463 } else {
1464 that.apiCheckValid();
1465 }
1466 } ).fail( function ( code, detail ) {
1467 that.$element.empty()
1468 .append(
1469 new OO.ui.LabelWidget( {
1470 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1471 classes: [ 'error' ]
1472 } ).$element,
1473 new OO.ui.ButtonWidget( {
1474 label: mw.message( 'apisandbox-retry' ).text()
1475 } ).on( 'click', that.loadParamInfo, [], that ).$element
1476 );
1477 } );
1478 };
1479
1480 /**
1481 * Check that all widgets on the page are in a valid state.
1482 *
1483 * @return {boolean}
1484 */
1485 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1486 var that = this;
1487
1488 if ( this.paramInfo === null ) {
1489 return $.Deferred().resolve( false ).promise();
1490 } else {
1491 return $.when.apply( $, $.map( this.widgets, function ( widget ) {
1492 return widget.apiCheckValid();
1493 } ) ).then( function () {
1494 that.apiIsValid = $.inArray( false, arguments ) === -1;
1495 if ( that.getOutlineItem() ) {
1496 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
1497 that.getOutlineItem().setIconTitle(
1498 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1499 );
1500 }
1501 return $.Deferred().resolve( that.apiIsValid ).promise();
1502 } );
1503 }
1504 };
1505
1506 /**
1507 * Load form fields from query parameters
1508 *
1509 * @param {Object} params
1510 */
1511 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
1512 if ( this.paramInfo === null ) {
1513 this.loadFromQueryParams = params;
1514 } else {
1515 $.each( this.widgets, function ( name, widget ) {
1516 var v = params.hasOwnProperty( name ) ? params[ name ] : undefined;
1517 widget.setApiValue( v );
1518 } );
1519 }
1520 };
1521
1522 /**
1523 * Load query params from form fields
1524 *
1525 * @param {Object} params Write query parameters into this object
1526 * @param {Object} displayParams Write query parameters for display into this object
1527 */
1528 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
1529 $.each( this.widgets, function ( name, widget ) {
1530 var value = widget.getApiValue();
1531 if ( value !== undefined ) {
1532 params[ name ] = value;
1533 if ( $.isFunction( widget.getApiValueForDisplay ) ) {
1534 value = widget.getApiValueForDisplay();
1535 }
1536 displayParams[ name ] = value;
1537 }
1538 } );
1539 };
1540
1541 /**
1542 * Fetch a list of subpage names loaded by this page
1543 *
1544 * @return {Array}
1545 */
1546 ApiSandbox.PageLayout.prototype.getSubpages = function () {
1547 var ret = [];
1548 $.each( this.widgets, function ( name, widget ) {
1549 var submodules, i;
1550 if ( $.isFunction( widget.getSubmodules ) ) {
1551 submodules = widget.getSubmodules();
1552 for ( i = 0; i < submodules.length; i++ ) {
1553 ret.push( {
1554 key: name + '=' + submodules[ i ].value,
1555 path: submodules[ i ].path,
1556 prefix: widget.paramInfo.submoduleparamprefix || ''
1557 } );
1558 }
1559 }
1560 } );
1561 return ret;
1562 };
1563
1564 /**
1565 * A text input with a clickable indicator
1566 *
1567 * @class
1568 * @private
1569 * @constructor
1570 * @param {Object} [config] Configuration options
1571 */
1572 function TextInputWithIndicatorWidget( config ) {
1573 var k;
1574
1575 config = config || {};
1576 TextInputWithIndicatorWidget[ 'super' ].call( this, config );
1577
1578 this.$indicator = $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1579 OO.ui.mixin.TabIndexedElement.call(
1580 this, $.extend( {}, config, { $tabIndexed: this.$indicator } )
1581 );
1582
1583 this.input = new OO.ui.TextInputWidget( $.extend( {
1584 $indicator: this.$indicator,
1585 disabled: this.isDisabled()
1586 }, config.input ) );
1587
1588 // Forward most methods for convenience
1589 for ( k in this.input ) {
1590 if ( $.isFunction( this.input[ k ] ) && !this[ k ] ) {
1591 this[ k ] = this.input[ k ].bind( this.input );
1592 }
1593 }
1594
1595 this.$indicator.on( {
1596 click: this.onIndicatorClick.bind( this ),
1597 keypress: this.onIndicatorKeyPress.bind( this )
1598 } );
1599
1600 this.$element.append( this.input.$element );
1601 }
1602 OO.inheritClass( TextInputWithIndicatorWidget, OO.ui.Widget );
1603 OO.mixinClass( TextInputWithIndicatorWidget, OO.ui.mixin.TabIndexedElement );
1604 TextInputWithIndicatorWidget.prototype.onIndicatorClick = function ( e ) {
1605 if ( !this.isDisabled() && e.which === 1 ) {
1606 this.emit( 'indicator' );
1607 }
1608 return false;
1609 };
1610 TextInputWithIndicatorWidget.prototype.onIndicatorKeyPress = function ( e ) {
1611 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
1612 this.emit( 'indicator' );
1613 return false;
1614 }
1615 };
1616 TextInputWithIndicatorWidget.prototype.setDisabled = function ( disabled ) {
1617 TextInputWithIndicatorWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1618 if ( this.input ) {
1619 this.input.setDisabled( this.isDisabled() );
1620 }
1621 return this;
1622 };
1623
1624 /**
1625 * A wrapper for a widget that provides an enable/disable button
1626 *
1627 * @class
1628 * @private
1629 * @constructor
1630 * @param {OO.ui.Widget} widget
1631 * @param {Object} [config] Configuration options
1632 */
1633 function OptionalWidget( widget, config ) {
1634 var k;
1635
1636 config = config || {};
1637
1638 this.widget = widget;
1639 this.$overlay = config.$overlay ||
1640 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1641 this.checkbox = new OO.ui.CheckboxInputWidget( config.checkbox )
1642 .on( 'change', this.onCheckboxChange, [], this );
1643
1644 OptionalWidget[ 'super' ].call( this, config );
1645
1646 // Forward most methods for convenience
1647 for ( k in this.widget ) {
1648 if ( $.isFunction( this.widget[ k ] ) && !this[ k ] ) {
1649 this[ k ] = this.widget[ k ].bind( this.widget );
1650 }
1651 }
1652
1653 this.$overlay.on( 'click', this.onOverlayClick.bind( this ) );
1654
1655 this.$element
1656 .addClass( 'mw-apisandbox-optionalWidget' )
1657 .append(
1658 this.$overlay,
1659 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1660 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1661 widget.$element
1662 ),
1663 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1664 this.checkbox.$element
1665 )
1666 )
1667 );
1668
1669 this.setDisabled( widget.isDisabled() );
1670 }
1671 OO.inheritClass( OptionalWidget, OO.ui.Widget );
1672 OptionalWidget.prototype.onCheckboxChange = function ( checked ) {
1673 this.setDisabled( !checked );
1674 };
1675 OptionalWidget.prototype.onOverlayClick = function () {
1676 this.setDisabled( false );
1677 if ( $.isFunction( this.widget.focus ) ) {
1678 this.widget.focus();
1679 }
1680 };
1681 OptionalWidget.prototype.setDisabled = function ( disabled ) {
1682 OptionalWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1683 this.widget.setDisabled( this.isDisabled() );
1684 this.checkbox.setSelected( !this.isDisabled() );
1685 this.$overlay.toggle( this.isDisabled() );
1686 return this;
1687 };
1688
1689 $( ApiSandbox.init );
1690
1691 module.exports = ApiSandbox;
1692
1693 }( jQuery, mediaWiki, OO ) );