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