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