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