Merge "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 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 $result.append( Util.parseHTML( data.html ) );
973 loadTime = data.time;
974 } else if ( ( m = data.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
975 $result.append( Util.parseHTML( m[ 0 ] ) );
976 if ( ( m = data.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
977 loadTime = parseInt( m[ 1 ], 10 );
978 }
979 } else {
980 $( '<pre>' )
981 .addClass( 'api-pretty-content' )
982 .text( data )
983 .appendTo( $result );
984 }
985 if ( paramsAreForced || data[ 'continue' ] ) {
986 $result.append(
987 $( '<div>' ).append(
988 new OO.ui.ButtonWidget( {
989 label: mw.message( 'apisandbox-continue' ).text()
990 } ).on( 'click', function () {
991 ApiSandbox.sendRequest( $.extend( {}, baseRequestParams, data[ 'continue' ] ) );
992 } ).setDisabled( !data[ 'continue' ] ).$element,
993 ( clear = new OO.ui.ButtonWidget( {
994 label: mw.message( 'apisandbox-continue-clear' ).text()
995 } ).on( 'click', function () {
996 ApiSandbox.updateUI( baseRequestParams );
997 clear.setDisabled( true );
998 booklet.setPage( '|results|' );
999 } ).setDisabled( !paramsAreForced ) ).$element,
1000 new OO.ui.PopupButtonWidget( {
1001 framed: false,
1002 icon: 'info',
1003 popup: {
1004 $content: $( '<div>' ).append( mw.message( 'apisandbox-continue-help' ).parse() ),
1005 padded: true
1006 }
1007 } ).$element
1008 )
1009 );
1010 }
1011 if ( typeof loadTime === 'number' ) {
1012 $result.append(
1013 $( '<div>' ).append(
1014 new OO.ui.LabelWidget( {
1015 label: mw.message( 'apisandbox-request-time', loadTime ).text()
1016 } ).$element
1017 )
1018 );
1019 }
1020
1021 if ( jqXHR.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1022 // Flush all saved tokens in case one of them is the bad one.
1023 Util.markTokensBad();
1024 button = new OO.ui.ButtonWidget( {
1025 label: mw.message( 'apisandbox-results-fixtoken' ).text()
1026 } );
1027 button.on( 'click', ApiSandbox.fixTokenAndResend )
1028 .on( 'click', button.setDisabled, [ true ], button )
1029 .$element.appendTo( $result );
1030 }
1031 } );
1032 } );
1033 },
1034
1035 /**
1036 * Handler for the "Correct token and resubmit" button
1037 *
1038 * Used on a 'badtoken' error, it re-fetches token parameters for all
1039 * pages and then re-submits the query.
1040 */
1041 fixTokenAndResend: function () {
1042 var page, subpages, i, k,
1043 ok = true,
1044 tokenWait = { dummy: true },
1045 checkPages = [ pages.main ],
1046 success = function ( k ) {
1047 delete tokenWait[ k ];
1048 if ( ok && $.isEmptyObject( tokenWait ) ) {
1049 ApiSandbox.sendRequest();
1050 }
1051 },
1052 failure = function ( k ) {
1053 delete tokenWait[ k ];
1054 ok = false;
1055 };
1056
1057 while ( checkPages.length ) {
1058 page = checkPages.shift();
1059
1060 if ( page.tokenWidget ) {
1061 k = page.apiModule + page.tokenWidget.paramInfo.name;
1062 tokenWait[ k ] = page.tokenWidget.fetchToken()
1063 .done( success.bind( page.tokenWidget, k ) )
1064 .fail( failure.bind( page.tokenWidget, k ) );
1065 }
1066
1067 subpages = page.getSubpages();
1068 for ( i = 0; i < subpages.length; i++ ) {
1069 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1070 checkPages.push( pages[ subpages[ i ].key ] );
1071 }
1072 }
1073 }
1074
1075 success( 'dummy', '' );
1076 },
1077
1078 /**
1079 * Reset validity indicators for all widgets
1080 */
1081 updateValidityIndicators: function () {
1082 var page, subpages, i,
1083 checkPages = [ pages.main ];
1084
1085 while ( checkPages.length ) {
1086 page = checkPages.shift();
1087 page.apiCheckValid();
1088 subpages = page.getSubpages();
1089 for ( i = 0; i < subpages.length; i++ ) {
1090 if ( pages.hasOwnProperty( subpages[ i ].key ) ) {
1091 checkPages.push( pages[ subpages[ i ].key ] );
1092 }
1093 }
1094 }
1095 }
1096 };
1097
1098 /**
1099 * PageLayout for API modules
1100 *
1101 * @class
1102 * @private
1103 * @extends OO.ui.PageLayout
1104 * @constructor
1105 * @param {Object} [config] Configuration options
1106 */
1107 ApiSandbox.PageLayout = function ( config ) {
1108 config = $.extend( { prefix: '' }, config );
1109 this.displayText = config.key;
1110 this.apiModule = config.path;
1111 this.prefix = config.prefix;
1112 this.paramInfo = null;
1113 this.apiIsValid = true;
1114 this.loadFromQueryParams = null;
1115 this.widgets = {};
1116 this.tokenWidget = null;
1117 this.indentLevel = config.indentLevel ? config.indentLevel : 0;
1118 ApiSandbox.PageLayout[ 'super' ].call( this, config.key, config );
1119 this.loadParamInfo();
1120 };
1121 OO.inheritClass( ApiSandbox.PageLayout, OO.ui.PageLayout );
1122 ApiSandbox.PageLayout.prototype.setupOutlineItem = function () {
1123 this.outlineItem.setLevel( this.indentLevel );
1124 this.outlineItem.setLabel( this.displayText );
1125 this.outlineItem.setIcon( this.apiIsValid || suppressErrors ? null : 'alert' );
1126 this.outlineItem.setIconTitle(
1127 this.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1128 );
1129 };
1130
1131 /**
1132 * Fetch module information for this page's module, then create UI
1133 */
1134 ApiSandbox.PageLayout.prototype.loadParamInfo = function () {
1135 var dynamicFieldset, dynamicParamNameWidget,
1136 that = this,
1137 removeDynamicParamWidget = function ( name, layout ) {
1138 dynamicFieldset.removeItems( [ layout ] );
1139 delete that.widgets[ name ];
1140 },
1141 addDynamicParamWidget = function () {
1142 var name, layout, widget, button;
1143
1144 // Check name is filled in
1145 name = dynamicParamNameWidget.getValue().trim();
1146 if ( name === '' ) {
1147 dynamicParamNameWidget.focus();
1148 return;
1149 }
1150
1151 if ( that.widgets[ name ] !== undefined ) {
1152 windowManager.openWindow( 'errorAlert', {
1153 title: mw.message(
1154 'apisandbox-dynamic-error-exists', name
1155 ).parse(),
1156 actions: [
1157 {
1158 action: 'accept',
1159 label: OO.ui.msg( 'ooui-dialog-process-dismiss' ),
1160 flags: 'primary'
1161 }
1162 ]
1163 } );
1164 return;
1165 }
1166
1167 widget = Util.createWidgetForParameter( {
1168 name: name,
1169 type: 'string',
1170 'default': ''
1171 }, {
1172 nooptional: true
1173 } );
1174 button = new OO.ui.ButtonWidget( {
1175 icon: 'remove',
1176 flags: 'destructive'
1177 } );
1178 layout = new OO.ui.ActionFieldLayout(
1179 widget,
1180 button,
1181 {
1182 label: name,
1183 align: 'left'
1184 }
1185 );
1186 button.on( 'click', removeDynamicParamWidget, [ name, layout ] );
1187 that.widgets[ name ] = widget;
1188 dynamicFieldset.addItems( [ layout ], dynamicFieldset.getItems().length - 1 );
1189 widget.focus();
1190
1191 dynamicParamNameWidget.setValue( '' );
1192 };
1193
1194 this.$element.empty()
1195 .append( new OO.ui.ProgressBarWidget( {
1196 progress: false,
1197 text: mw.message( 'apisandbox-loading', this.displayText ).text()
1198 } ).$element );
1199
1200 Util.fetchModuleInfo( this.apiModule )
1201 .done( function ( pi ) {
1202 var prefix, i, j, dl, widget, $widgetLabel, widgetField, helpField, tmp, flag, count,
1203 items = [],
1204 deprecatedItems = [],
1205 buttons = [],
1206 filterFmModules = function ( v ) {
1207 return v.substr( -2 ) !== 'fm' ||
1208 !availableFormats.hasOwnProperty( v.substr( 0, v.length - 2 ) );
1209 },
1210 widgetLabelOnClick = function () {
1211 var f = this.getField();
1212 if ( $.isFunction( f.setDisabled ) ) {
1213 f.setDisabled( false );
1214 }
1215 if ( $.isFunction( f.focus ) ) {
1216 f.focus();
1217 }
1218 },
1219 doNothing = function () {};
1220
1221 // This is something of a hack. We always want the 'format' and
1222 // 'action' parameters from the main module to be specified,
1223 // and for 'format' we also want to simplify the dropdown since
1224 // we always send the 'fm' variant.
1225 if ( that.apiModule === 'main' ) {
1226 for ( i = 0; i < pi.parameters.length; i++ ) {
1227 if ( pi.parameters[ i ].name === 'action' ) {
1228 pi.parameters[ i ].required = true;
1229 delete pi.parameters[ i ][ 'default' ];
1230 }
1231 if ( pi.parameters[ i ].name === 'format' ) {
1232 tmp = pi.parameters[ i ].type;
1233 for ( j = 0; j < tmp.length; j++ ) {
1234 availableFormats[ tmp[ j ] ] = true;
1235 }
1236 pi.parameters[ i ].type = $.grep( tmp, filterFmModules );
1237 pi.parameters[ i ][ 'default' ] = 'json';
1238 pi.parameters[ i ].required = true;
1239 }
1240 }
1241 }
1242
1243 // Hide the 'wrappedhtml' parameter on format modules
1244 if ( pi.group === 'format' ) {
1245 pi.parameters = $.grep( pi.parameters, function ( p ) {
1246 return p.name !== 'wrappedhtml';
1247 } );
1248 }
1249
1250 that.paramInfo = pi;
1251
1252 items.push( new OO.ui.FieldLayout(
1253 new OO.ui.Widget( {} ).toggle( false ), {
1254 align: 'top',
1255 label: Util.parseHTML( pi.description )
1256 }
1257 ) );
1258
1259 if ( pi.helpurls.length ) {
1260 buttons.push( new OO.ui.PopupButtonWidget( {
1261 label: mw.message( 'apisandbox-helpurls' ).text(),
1262 icon: 'help',
1263 popup: {
1264 $content: $( '<ul>' ).append( $.map( pi.helpurls, function ( link ) {
1265 return $( '<li>' ).append( $( '<a>', {
1266 href: link,
1267 target: '_blank',
1268 text: link
1269 } ) );
1270 } ) )
1271 }
1272 } ) );
1273 }
1274
1275 if ( pi.examples.length ) {
1276 buttons.push( new OO.ui.PopupButtonWidget( {
1277 label: mw.message( 'apisandbox-examples' ).text(),
1278 icon: 'code',
1279 popup: {
1280 $content: $( '<ul>' ).append( $.map( pi.examples, function ( example ) {
1281 var a = $( '<a>', {
1282 href: '#' + example.query,
1283 html: example.description
1284 } );
1285 a.find( 'a' ).contents().unwrap(); // Can't nest links
1286 return $( '<li>' ).append( a );
1287 } ) )
1288 }
1289 } ) );
1290 }
1291
1292 if ( buttons.length ) {
1293 items.push( new OO.ui.FieldLayout(
1294 new OO.ui.ButtonGroupWidget( {
1295 items: buttons
1296 } ), { align: 'top' }
1297 ) );
1298 }
1299
1300 if ( pi.parameters.length ) {
1301 prefix = that.prefix + pi.prefix;
1302 for ( i = 0; i < pi.parameters.length; i++ ) {
1303 widget = Util.createWidgetForParameter( pi.parameters[ i ] );
1304 that.widgets[ prefix + pi.parameters[ i ].name ] = widget;
1305 if ( pi.parameters[ i ].tokentype ) {
1306 that.tokenWidget = widget;
1307 }
1308
1309 dl = $( '<dl>' );
1310 dl.append( $( '<dd>', {
1311 addClass: 'description',
1312 append: Util.parseHTML( pi.parameters[ i ].description )
1313 } ) );
1314 if ( pi.parameters[ i ].info && pi.parameters[ i ].info.length ) {
1315 for ( j = 0; j < pi.parameters[ i ].info.length; j++ ) {
1316 dl.append( $( '<dd>', {
1317 addClass: 'info',
1318 append: Util.parseHTML( pi.parameters[ i ].info[ j ] )
1319 } ) );
1320 }
1321 }
1322 flag = true;
1323 count = 1e100;
1324 switch ( pi.parameters[ i ].type ) {
1325 case 'namespace':
1326 flag = false;
1327 count = mw.config.get( 'wgFormattedNamespaces' ).length;
1328 break;
1329
1330 case 'limit':
1331 if ( pi.parameters[ i ].highmax !== undefined ) {
1332 dl.append( $( '<dd>', {
1333 addClass: 'info',
1334 append: Util.parseHTML( mw.message(
1335 'api-help-param-limit2', pi.parameters[ i ].max, pi.parameters[ i ].highmax
1336 ).parse() )
1337 } ) );
1338 } else {
1339 dl.append( $( '<dd>', {
1340 addClass: 'info',
1341 append: Util.parseHTML( mw.message(
1342 'api-help-param-limit', pi.parameters[ i ].max
1343 ).parse() )
1344 } ) );
1345 }
1346 break;
1347
1348 case 'integer':
1349 tmp = '';
1350 if ( pi.parameters[ i ].min !== undefined ) {
1351 tmp += 'min';
1352 }
1353 if ( pi.parameters[ i ].max !== undefined ) {
1354 tmp += 'max';
1355 }
1356 if ( tmp !== '' ) {
1357 dl.append( $( '<dd>', {
1358 addClass: 'info',
1359 append: Util.parseHTML( mw.message(
1360 'api-help-param-integer-' + tmp,
1361 Util.apiBool( pi.parameters[ i ].multi ) ? 2 : 1,
1362 pi.parameters[ i ].min, pi.parameters[ i ].max
1363 ).parse() )
1364 } ) );
1365 }
1366 break;
1367
1368 default:
1369 if ( $.isArray( pi.parameters[ i ].type ) ) {
1370 flag = false;
1371 count = pi.parameters[ i ].type.length;
1372 }
1373 break;
1374 }
1375 if ( Util.apiBool( pi.parameters[ i ].multi ) ) {
1376 tmp = [];
1377 if ( flag && !( widget instanceof OO.ui.CapsuleMultiselectWidget ) &&
1378 !(
1379 widget instanceof OptionalWidget &&
1380 widget.widget instanceof OO.ui.CapsuleMultiselectWidget
1381 )
1382 ) {
1383 tmp.push( mw.message( 'api-help-param-multi-separate' ).parse() );
1384 }
1385 if ( count > pi.parameters[ i ].lowlimit ) {
1386 tmp.push(
1387 mw.message( 'api-help-param-multi-max',
1388 pi.parameters[ i ].lowlimit, pi.parameters[ i ].highlimit
1389 ).parse()
1390 );
1391 }
1392 if ( tmp.length ) {
1393 dl.append( $( '<dd>', {
1394 addClass: 'info',
1395 append: Util.parseHTML( tmp.join( ' ' ) )
1396 } ) );
1397 }
1398 }
1399 helpField = new OO.ui.FieldLayout(
1400 new OO.ui.Widget( {
1401 $content: '\xa0',
1402 classes: [ 'mw-apisandbox-spacer' ]
1403 } ), {
1404 align: 'inline',
1405 classes: [ 'mw-apisandbox-help-field' ],
1406 label: dl
1407 }
1408 );
1409
1410 $widgetLabel = $( '<span>' );
1411 widgetField = new OO.ui.FieldLayout(
1412 widget,
1413 {
1414 align: 'left',
1415 classes: [ 'mw-apisandbox-widget-field' ],
1416 label: prefix + pi.parameters[ i ].name,
1417 $label: $widgetLabel
1418 }
1419 );
1420
1421 // FieldLayout only does click for InputElement
1422 // widgets. So supply our own click handler.
1423 $widgetLabel.on( 'click', widgetLabelOnClick.bind( widgetField ) );
1424
1425 // Don't grey out the label when the field is disabled,
1426 // it makes it too hard to read and our "disabled"
1427 // isn't really disabled.
1428 widgetField.onFieldDisable( false );
1429 widgetField.onFieldDisable = doNothing;
1430
1431 if ( Util.apiBool( pi.parameters[ i ].deprecated ) ) {
1432 deprecatedItems.push( widgetField, helpField );
1433 } else {
1434 items.push( widgetField, helpField );
1435 }
1436 }
1437 }
1438
1439 if ( !pi.parameters.length && !Util.apiBool( pi.dynamicparameters ) ) {
1440 items.push( new OO.ui.FieldLayout(
1441 new OO.ui.Widget( {} ).toggle( false ), {
1442 align: 'top',
1443 label: Util.parseHTML( mw.message( 'apisandbox-no-parameters' ).parse() )
1444 }
1445 ) );
1446 }
1447
1448 that.$element.empty();
1449
1450 new OO.ui.FieldsetLayout( {
1451 label: that.displayText
1452 } ).addItems( items )
1453 .$element.appendTo( that.$element );
1454
1455 if ( Util.apiBool( pi.dynamicparameters ) ) {
1456 dynamicFieldset = new OO.ui.FieldsetLayout();
1457 dynamicParamNameWidget = new OO.ui.TextInputWidget( {
1458 placeholder: mw.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1459 } ).on( 'enter', addDynamicParamWidget );
1460 dynamicFieldset.addItems( [
1461 new OO.ui.FieldLayout(
1462 new OO.ui.Widget( {} ).toggle( false ), {
1463 align: 'top',
1464 label: Util.parseHTML( pi.dynamicparameters )
1465 }
1466 ),
1467 new OO.ui.ActionFieldLayout(
1468 dynamicParamNameWidget,
1469 new OO.ui.ButtonWidget( {
1470 icon: 'add',
1471 flags: 'progressive'
1472 } ).on( 'click', addDynamicParamWidget ),
1473 {
1474 label: mw.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1475 align: 'left'
1476 }
1477 )
1478 ] );
1479 $( '<fieldset>' )
1480 .append(
1481 $( '<legend>' ).text( mw.message( 'apisandbox-dynamic-parameters' ).text() ),
1482 dynamicFieldset.$element
1483 )
1484 .appendTo( that.$element );
1485 }
1486
1487 if ( deprecatedItems.length ) {
1488 tmp = new OO.ui.FieldsetLayout().addItems( deprecatedItems ).toggle( false );
1489 $( '<fieldset>' )
1490 .append(
1491 $( '<legend>' ).append(
1492 new OO.ui.ToggleButtonWidget( {
1493 label: mw.message( 'apisandbox-deprecated-parameters' ).text()
1494 } ).on( 'change', tmp.toggle, [], tmp ).$element
1495 ),
1496 tmp.$element
1497 )
1498 .appendTo( that.$element );
1499 }
1500
1501 // Load stored params, if any, then update the booklet if we
1502 // have subpages (or else just update our valid-indicator).
1503 tmp = that.loadFromQueryParams;
1504 that.loadFromQueryParams = null;
1505 if ( $.isPlainObject( tmp ) ) {
1506 that.loadQueryParams( tmp );
1507 }
1508 if ( that.getSubpages().length > 0 ) {
1509 ApiSandbox.updateUI( tmp );
1510 } else {
1511 that.apiCheckValid();
1512 }
1513 } ).fail( function ( code, detail ) {
1514 that.$element.empty()
1515 .append(
1516 new OO.ui.LabelWidget( {
1517 label: mw.message( 'apisandbox-load-error', that.apiModule, detail ).text(),
1518 classes: [ 'error' ]
1519 } ).$element,
1520 new OO.ui.ButtonWidget( {
1521 label: mw.message( 'apisandbox-retry' ).text()
1522 } ).on( 'click', that.loadParamInfo, [], that ).$element
1523 );
1524 } );
1525 };
1526
1527 /**
1528 * Check that all widgets on the page are in a valid state.
1529 *
1530 * @return {boolean}
1531 */
1532 ApiSandbox.PageLayout.prototype.apiCheckValid = function () {
1533 var that = this;
1534
1535 if ( this.paramInfo === null ) {
1536 return $.Deferred().resolve( false ).promise();
1537 } else {
1538 return $.when.apply( $, $.map( this.widgets, function ( widget ) {
1539 return widget.apiCheckValid();
1540 } ) ).then( function () {
1541 that.apiIsValid = $.inArray( false, arguments ) === -1;
1542 if ( that.getOutlineItem() ) {
1543 that.getOutlineItem().setIcon( that.apiIsValid || suppressErrors ? null : 'alert' );
1544 that.getOutlineItem().setIconTitle(
1545 that.apiIsValid || suppressErrors ? '' : mw.message( 'apisandbox-alert-page' ).plain()
1546 );
1547 }
1548 return $.Deferred().resolve( that.apiIsValid ).promise();
1549 } );
1550 }
1551 };
1552
1553 /**
1554 * Load form fields from query parameters
1555 *
1556 * @param {Object} params
1557 */
1558 ApiSandbox.PageLayout.prototype.loadQueryParams = function ( params ) {
1559 if ( this.paramInfo === null ) {
1560 this.loadFromQueryParams = params;
1561 } else {
1562 $.each( this.widgets, function ( name, widget ) {
1563 var v = params.hasOwnProperty( name ) ? params[ name ] : undefined;
1564 widget.setApiValue( v );
1565 } );
1566 }
1567 };
1568
1569 /**
1570 * Load query params from form fields
1571 *
1572 * @param {Object} params Write query parameters into this object
1573 * @param {Object} displayParams Write query parameters for display into this object
1574 */
1575 ApiSandbox.PageLayout.prototype.getQueryParams = function ( params, displayParams ) {
1576 $.each( this.widgets, function ( name, widget ) {
1577 var value = widget.getApiValue();
1578 if ( value !== undefined ) {
1579 params[ name ] = value;
1580 if ( $.isFunction( widget.getApiValueForDisplay ) ) {
1581 value = widget.getApiValueForDisplay();
1582 }
1583 displayParams[ name ] = value;
1584 }
1585 } );
1586 };
1587
1588 /**
1589 * Fetch a list of subpage names loaded by this page
1590 *
1591 * @return {Array}
1592 */
1593 ApiSandbox.PageLayout.prototype.getSubpages = function () {
1594 var ret = [];
1595 $.each( this.widgets, function ( name, widget ) {
1596 var submodules, i;
1597 if ( $.isFunction( widget.getSubmodules ) ) {
1598 submodules = widget.getSubmodules();
1599 for ( i = 0; i < submodules.length; i++ ) {
1600 ret.push( {
1601 key: name + '=' + submodules[ i ].value,
1602 path: submodules[ i ].path,
1603 prefix: widget.paramInfo.submoduleparamprefix || ''
1604 } );
1605 }
1606 }
1607 } );
1608 return ret;
1609 };
1610
1611 /**
1612 * A text input with a clickable indicator
1613 *
1614 * @class
1615 * @private
1616 * @constructor
1617 * @param {Object} [config] Configuration options
1618 */
1619 function TextInputWithIndicatorWidget( config ) {
1620 var k;
1621
1622 config = config || {};
1623 TextInputWithIndicatorWidget[ 'super' ].call( this, config );
1624
1625 this.$indicator = $( '<span>' ).addClass( 'mw-apisandbox-clickable-indicator' );
1626 OO.ui.mixin.TabIndexedElement.call(
1627 this, $.extend( {}, config, { $tabIndexed: this.$indicator } )
1628 );
1629
1630 this.input = new OO.ui.TextInputWidget( $.extend( {
1631 $indicator: this.$indicator,
1632 disabled: this.isDisabled()
1633 }, config.input ) );
1634
1635 // Forward most methods for convenience
1636 for ( k in this.input ) {
1637 if ( $.isFunction( this.input[ k ] ) && !this[ k ] ) {
1638 this[ k ] = this.input[ k ].bind( this.input );
1639 }
1640 }
1641
1642 this.$indicator.on( {
1643 click: this.onIndicatorClick.bind( this ),
1644 keypress: this.onIndicatorKeyPress.bind( this )
1645 } );
1646
1647 this.$element.append( this.input.$element );
1648 }
1649 OO.inheritClass( TextInputWithIndicatorWidget, OO.ui.Widget );
1650 OO.mixinClass( TextInputWithIndicatorWidget, OO.ui.mixin.TabIndexedElement );
1651 TextInputWithIndicatorWidget.prototype.onIndicatorClick = function ( e ) {
1652 if ( !this.isDisabled() && e.which === 1 ) {
1653 this.emit( 'indicator' );
1654 }
1655 return false;
1656 };
1657 TextInputWithIndicatorWidget.prototype.onIndicatorKeyPress = function ( e ) {
1658 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
1659 this.emit( 'indicator' );
1660 return false;
1661 }
1662 };
1663 TextInputWithIndicatorWidget.prototype.setDisabled = function ( disabled ) {
1664 TextInputWithIndicatorWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1665 if ( this.input ) {
1666 this.input.setDisabled( this.isDisabled() );
1667 }
1668 return this;
1669 };
1670
1671 /**
1672 * A wrapper for a widget that provides an enable/disable button
1673 *
1674 * @class
1675 * @private
1676 * @constructor
1677 * @param {OO.ui.Widget} widget
1678 * @param {Object} [config] Configuration options
1679 */
1680 function OptionalWidget( widget, config ) {
1681 var k;
1682
1683 config = config || {};
1684
1685 this.widget = widget;
1686 this.$overlay = config.$overlay ||
1687 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-overlay' );
1688 this.checkbox = new OO.ui.CheckboxInputWidget( config.checkbox )
1689 .on( 'change', this.onCheckboxChange, [], this );
1690
1691 OptionalWidget[ 'super' ].call( this, config );
1692
1693 // Forward most methods for convenience
1694 for ( k in this.widget ) {
1695 if ( $.isFunction( this.widget[ k ] ) && !this[ k ] ) {
1696 this[ k ] = this.widget[ k ].bind( this.widget );
1697 }
1698 }
1699
1700 this.$overlay.on( 'click', this.onOverlayClick.bind( this ) );
1701
1702 this.$element
1703 .addClass( 'mw-apisandbox-optionalWidget' )
1704 .append(
1705 this.$overlay,
1706 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1707 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1708 widget.$element
1709 ),
1710 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1711 this.checkbox.$element
1712 )
1713 )
1714 );
1715
1716 this.setDisabled( widget.isDisabled() );
1717 }
1718 OO.inheritClass( OptionalWidget, OO.ui.Widget );
1719 OptionalWidget.prototype.onCheckboxChange = function ( checked ) {
1720 this.setDisabled( !checked );
1721 };
1722 OptionalWidget.prototype.onOverlayClick = function () {
1723 this.setDisabled( false );
1724 if ( $.isFunction( this.widget.focus ) ) {
1725 this.widget.focus();
1726 }
1727 };
1728 OptionalWidget.prototype.setDisabled = function ( disabled ) {
1729 OptionalWidget[ 'super' ].prototype.setDisabled.call( this, disabled );
1730 this.widget.setDisabled( this.isDisabled() );
1731 this.checkbox.setSelected( !this.isDisabled() );
1732 this.$overlay.toggle( this.isDisabled() );
1733 return this;
1734 };
1735
1736 $( ApiSandbox.init );
1737
1738 module.exports = ApiSandbox;
1739
1740 }( jQuery, mediaWiki, OO ) );