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