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