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