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