516551c1c7f7f8ed80926294aa85378410bdacc9
1 ( function ( $, mw
, OO
) {
3 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
4 $content
, panel
, booklet
, oldhash
, windowManager
, fullscreenButton
,
10 suppressErrors
= true,
11 updatingBooklet
= false,
17 * A wrapper for a widget that provides an enable/disable button
22 * @param {OO.ui.Widget} widget
23 * @param {Object} [config] Configuration options
25 function OptionalWidget( widget
, config
) {
28 config
= config
|| {};
31 this.$cover
= config
.$cover
||
32 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-cover' );
33 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
34 .on( 'change', this.onCheckboxChange
, [], this );
36 OptionalWidget
[ 'super' ].call( this, config
);
38 // Forward most methods for convenience
39 for ( k
in this.widget
) {
40 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
41 this[ k
] = this.widget
[ k
].bind( this.widget
);
45 this.$cover
.on( 'click', this.onOverlayClick
.bind( this ) );
48 .addClass( 'mw-apisandbox-optionalWidget' )
51 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
52 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
55 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
56 this.checkbox
.$element
61 this.setDisabled( widget
.isDisabled() );
63 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
64 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
65 this.setDisabled( !checked
);
67 OptionalWidget
.prototype.onOverlayClick = function () {
68 this.setDisabled( false );
69 if ( $.isFunction( this.widget
.focus
) ) {
73 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
74 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
75 this.widget
.setDisabled( this.isDisabled() );
76 this.checkbox
.setSelected( !this.isDisabled() );
77 this.$cover
.toggle( this.isDisabled() );
83 getApiValue: function () {
84 return this.getValue();
86 setApiValue: function ( v
) {
87 if ( v
=== undefined ) {
88 v
= this.paramInfo
[ 'default' ];
92 apiCheckValid: function () {
94 return this.getValidity().then( function () {
95 return $.Deferred().resolve( true ).promise();
97 return $.Deferred().resolve( false ).promise();
98 } ).done( function ( ok
) {
99 ok
= ok
|| suppressErrors
;
100 that
.setIcon( ok
? null : 'alert' );
101 that
.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
106 dateTimeInputWidget
: {
107 getValidity: function () {
108 if ( !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '' ) {
109 return $.Deferred().resolve().promise();
111 return $.Deferred().reject().promise();
117 alertTokenError: function ( code
, error
) {
118 windowManager
.openWindow( 'errorAlert', {
119 title
: Util
.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo
.tokentype
),
124 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
130 fetchToken: function () {
132 return api
.getToken( this.paramInfo
.tokentype
)
133 .done( this.setApiValue
.bind( this ) )
134 .fail( this.alertTokenError
.bind( this ) )
135 .always( this.popPending
.bind( this ) );
137 setApiValue: function ( v
) {
138 WidgetMethods
.textInputWidget
.setApiValue
.call( this, v
);
139 if ( v
=== '123ABC' ) {
146 getApiValueForDisplay: function () {
151 toggleSwitchWidget
: {
152 getApiValue: function () {
153 return this.getValue() ? 1 : undefined;
155 setApiValue: function ( v
) {
156 this.setValue( Util
.apiBool( v
) );
158 apiCheckValid: function () {
159 return $.Deferred().resolve( true ).promise();
164 getApiValue: function () {
165 var item
= this.getMenu().findSelectedItem();
166 return item
=== null ? undefined : item
.getData();
168 setApiValue: function ( v
) {
169 var menu
= this.getMenu();
171 if ( v
=== undefined ) {
172 v
= this.paramInfo
[ 'default' ];
174 if ( v
=== undefined ) {
177 menu
.selectItemByData( String( v
) );
180 apiCheckValid: function () {
181 var ok
= this.getApiValue() !== undefined || suppressErrors
;
182 this.setIcon( ok
? null : 'alert' );
183 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
184 return $.Deferred().resolve( ok
).promise();
189 getApiValue: function () {
190 var items
= this.getValue();
191 if ( items
.join( '' ).indexOf( '|' ) === -1 ) {
192 return items
.join( '|' );
194 return '\x1f' + items
.join( '\x1f' );
197 setApiValue: function ( v
) {
198 if ( v
=== undefined || v
=== '' || v
=== '\x1f' ) {
202 if ( v
.indexOf( '\x1f' ) !== 0 ) {
203 this.setValue( v
.split( '|' ) );
205 this.setValue( v
.substr( 1 ).split( '\x1f' ) );
209 apiCheckValid: function () {
213 if ( !suppressErrors
) {
214 ok
= this.getApiValue() !== undefined && !(
215 pi
.allspecifier
!== undefined &&
216 this.getValue().length
> 1 &&
217 this.getValue().indexOf( pi
.allspecifier
) !== -1
221 this.setIcon( ok
? null : 'alert' );
222 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
223 return $.Deferred().resolve( ok
).promise();
225 createTagItemWidget: function ( data
, label
) {
226 var item
= OO
.ui
.TagMultiselectWidget
.prototype.createTagItemWidget
.call( this, data
, label
);
227 if ( this.paramInfo
.deprecatedvalues
&&
228 this.paramInfo
.deprecatedvalues
.indexOf( data
) >= 0
230 item
.$element
.addClass( 'apihelp-deprecated-value' );
237 getApiValue: function () {
238 return this.isDisabled() ? undefined : this.widget
.getApiValue();
240 setApiValue: function ( v
) {
241 this.setDisabled( v
=== undefined );
242 this.widget
.setApiValue( v
);
244 apiCheckValid: function () {
245 if ( this.isDisabled() ) {
246 return $.Deferred().resolve( true ).promise();
248 return this.widget
.apiCheckValid();
254 single: function () {
255 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
256 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
259 var map
= this.paramInfo
.submodules
,
260 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
261 return v
=== undefined || v
=== '' ? [] : String( v
).split( '|' ).map( function ( v
) {
262 return { value
: v
, path
: map
[ v
] };
268 getApiValueForDisplay: function () {
271 getApiValue: function () {
272 return this.getValue();
274 setApiValue: function () {
277 apiCheckValid: function () {
278 var ok
= this.getValue() !== null || suppressErrors
;
279 this.setIcon( ok
? null : 'alert' );
280 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
281 return $.Deferred().resolve( ok
).promise();
287 generic: function () {
288 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
293 * @class mw.special.ApiSandbox.Util
298 * Fetch API module info
300 * @param {string} module Module to fetch data for
301 * @return {jQuery.Promise}
303 fetchModuleInfo: function ( module
) {
305 deferred
= $.Deferred();
307 if ( moduleInfoCache
.hasOwnProperty( module
) ) {
309 .resolve( moduleInfoCache
[ module
] )
310 .promise( { abort: function () {} } );
312 apiPromise
= api
.post( {
316 uselang
: mw
.config
.get( 'wgUserLanguage' )
317 } ).done( function ( data
) {
320 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
321 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
325 info
= data
.paraminfo
.modules
;
326 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
327 deferred
.reject( '???', 'No module data returned' );
331 moduleInfoCache
[ module
] = info
[ 0 ];
332 deferred
.resolve( info
[ 0 ] );
333 } ).fail( function ( code
, details
) {
334 if ( code
=== 'http' ) {
335 details
= 'HTTP error: ' + details
.exception
;
336 } else if ( details
.error
) {
337 details
= details
.error
.info
;
339 deferred
.reject( code
, details
);
342 .promise( { abort
: apiPromise
.abort
} );
347 * Mark all currently-in-use tokens as bad
349 markTokensBad: function () {
350 var page
, subpages
, i
,
351 checkPages
= [ pages
.main
];
353 while ( checkPages
.length
) {
354 page
= checkPages
.shift();
356 if ( page
.tokenWidget
) {
357 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
360 subpages
= page
.getSubpages();
361 for ( i
= 0; i
< subpages
.length
; i
++ ) {
362 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
363 checkPages
.push( pages
[ subpages
[ i
].key
] );
370 * Test an API boolean
372 * @param {Mixed} value
375 apiBool: function ( value
) {
376 return value
!== undefined && value
!== false;
380 * Create a widget for a parameter.
382 * @param {Object} pi Parameter info from API
383 * @param {Object} opts Additional options
384 * @return {OO.ui.Widget}
386 createWidgetForParameter: function ( pi
, opts
) {
387 var widget
, innerWidget
, finalWidget
, items
, $content
, func
,
388 multiModeButton
= null,
389 multiModeInput
= null,
390 multiModeAllowed
= false;
396 widget
= new OO
.ui
.ToggleSwitchWidget();
397 widget
.paramInfo
= pi
;
398 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
399 pi
.required
= true; // Avoid wrapping in the non-required widget
404 if ( Util
.apiBool( pi
.multi
) ) {
405 widget
= new OO
.ui
.TagMultiselectWidget( {
406 allowArbitrary
: true,
407 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
410 widget
.paramInfo
= pi
;
411 $.extend( widget
, WidgetMethods
.tagWidget
);
413 widget
= new OO
.ui
.TextInputWidget( {
414 required
: Util
.apiBool( pi
.required
)
417 if ( !Util
.apiBool( pi
.multi
) ) {
418 widget
.paramInfo
= pi
;
419 $.extend( widget
, WidgetMethods
.textInputWidget
);
420 widget
.setValidation( Validators
.generic
);
422 if ( pi
.tokentype
) {
423 widget
.paramInfo
= pi
;
424 $.extend( widget
, WidgetMethods
.textInputWidget
);
425 $.extend( widget
, WidgetMethods
.tokenWidget
);
430 widget
= new OO
.ui
.MultilineTextInputWidget( {
431 required
: Util
.apiBool( pi
.required
)
433 widget
.paramInfo
= pi
;
434 $.extend( widget
, WidgetMethods
.textInputWidget
);
435 widget
.setValidation( Validators
.generic
);
439 widget
= new OO
.ui
.TextInputWidget( {
441 required
: Util
.apiBool( pi
.required
)
443 widget
.paramInfo
= pi
;
444 $.extend( widget
, WidgetMethods
.textInputWidget
);
445 $.extend( widget
, WidgetMethods
.passwordWidget
);
446 widget
.setValidation( Validators
.generic
);
447 multiModeAllowed
= true;
448 multiModeInput
= widget
;
452 widget
= new OO
.ui
.NumberInputWidget( {
453 required
: Util
.apiBool( pi
.required
),
456 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
457 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
458 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
459 widget
.paramInfo
= pi
;
460 $.extend( widget
, WidgetMethods
.textInputWidget
);
461 if ( Util
.apiBool( pi
.enforcerange
) ) {
462 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
464 multiModeAllowed
= true;
465 multiModeInput
= widget
;
469 widget
= new OO
.ui
.TextInputWidget( {
470 required
: Util
.apiBool( pi
.required
)
472 widget
.setValidation( function ( value
) {
473 var n
, pi
= this.paramInfo
;
475 if ( value
=== 'max' ) {
479 return !isNaN( n
) && isFinite( n
) &&
480 Math
.floor( n
) === n
&&
481 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
484 pi
.min
= pi
.min
|| 0;
485 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
486 widget
.paramInfo
= pi
;
487 $.extend( widget
, WidgetMethods
.textInputWidget
);
488 multiModeAllowed
= true;
489 multiModeInput
= widget
;
493 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
495 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
497 required
: Util
.apiBool( pi
.required
),
500 widget
.paramInfo
= pi
;
501 $.extend( widget
, WidgetMethods
.textInputWidget
);
502 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
503 multiModeAllowed
= true;
507 widget
= new OO
.ui
.SelectFileWidget();
508 widget
.paramInfo
= pi
;
509 $.extend( widget
, WidgetMethods
.uploadWidget
);
513 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
515 name
= mw
.message( 'blanknamespace' ).text();
517 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
518 } ).sort( function ( a
, b
) {
519 return a
.data
- b
.data
;
521 if ( Util
.apiBool( pi
.multi
) ) {
522 if ( pi
.allspecifier
!== undefined ) {
523 items
.unshift( new OO
.ui
.MenuOptionWidget( {
524 data
: pi
.allspecifier
,
525 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
529 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
530 menu
: { items
: items
},
533 widget
.paramInfo
= pi
;
534 $.extend( widget
, WidgetMethods
.tagWidget
);
536 widget
= new OO
.ui
.DropdownWidget( {
537 menu
: { items
: items
},
540 widget
.paramInfo
= pi
;
541 $.extend( widget
, WidgetMethods
.dropdownWidget
);
546 if ( !Array
.isArray( pi
.type
) ) {
547 throw new Error( 'Unknown parameter type ' + pi
.type
);
550 items
= pi
.type
.map( function ( v
) {
556 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
557 config
.classes
.push( 'apihelp-deprecated-value' );
559 return new OO
.ui
.MenuOptionWidget( config
);
561 if ( Util
.apiBool( pi
.multi
) ) {
562 if ( pi
.allspecifier
!== undefined ) {
563 items
.unshift( new OO
.ui
.MenuOptionWidget( {
564 data
: pi
.allspecifier
,
565 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
569 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
570 menu
: { items
: items
},
573 widget
.paramInfo
= pi
;
574 $.extend( widget
, WidgetMethods
.tagWidget
);
575 if ( Util
.apiBool( pi
.submodules
) ) {
576 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
577 widget
.on( 'change', ApiSandbox
.updateUI
);
580 widget
= new OO
.ui
.DropdownWidget( {
581 menu
: { items
: items
},
584 widget
.paramInfo
= pi
;
585 $.extend( widget
, WidgetMethods
.dropdownWidget
);
586 if ( Util
.apiBool( pi
.submodules
) ) {
587 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
588 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
590 if ( pi
.deprecatedvalues
) {
591 widget
.getMenu().on( 'select', function ( item
) {
592 this.$element
.toggleClass(
593 'apihelp-deprecated-value',
594 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
603 if ( Util
.apiBool( pi
.multi
) && multiModeAllowed
) {
604 innerWidget
= widget
;
606 multiModeButton
= new OO
.ui
.ButtonWidget( {
607 label
: mw
.message( 'apisandbox-add-multi' ).text()
609 $content
= innerWidget
.$element
.add( multiModeButton
.$element
);
611 widget
= new OO
.ui
.PopupTagMultiselectWidget( {
612 allowArbitrary
: true,
613 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
616 classes
: [ 'mw-apisandbox-popup' ],
620 widget
.paramInfo
= pi
;
621 $.extend( widget
, WidgetMethods
.tagWidget
);
624 if ( !innerWidget
.isDisabled() ) {
625 innerWidget
.apiCheckValid().done( function ( ok
) {
627 widget
.addTag( innerWidget
.getApiValue() );
628 innerWidget
.setApiValue( undefined );
635 if ( multiModeInput
) {
636 multiModeInput
.on( 'enter', func
);
638 multiModeButton
.on( 'click', func
);
641 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
642 finalWidget
= widget
;
644 finalWidget
= new OptionalWidget( widget
);
645 finalWidget
.paramInfo
= pi
;
646 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
647 if ( widget
.getSubmodules
) {
648 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
649 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
651 finalWidget
.setDisabled( true );
654 widget
.setApiValue( pi
[ 'default' ] );
660 * Parse an HTML string and call Util.fixupHTML()
662 * @param {string} html HTML to parse
665 parseHTML: function ( html
) {
666 var $ret
= $( $.parseHTML( html
) );
667 return Util
.fixupHTML( $ret
);
671 * Parse an i18n message and call Util.fixupHTML()
673 * @param {string} key Key of message to get
674 * @param {...Mixed} parameters Values for $N replacements
677 parseMsg: function () {
678 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
679 return Util
.fixupHTML( $ret
);
683 * Fix HTML for ApiSandbox display
686 * - Add target="_blank" to any links
688 * @param {jQuery} $html DOM to process
691 fixupHTML: function ( $html
) {
692 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
693 .filter( '[href]:not([target])' )
694 .attr( 'target', '_blank' );
699 * Format a request and return a bunch of menu option widgets
701 * @param {Object} displayParams Query parameters, sanitized for display.
702 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
703 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
705 formatRequest: function ( displayParams
, rawParams
) {
708 new OO
.ui
.MenuOptionWidget( {
709 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
710 data
: new OO
.ui
.FieldLayout(
711 new OO
.ui
.TextInputWidget( {
713 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
715 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
719 new OO
.ui
.MenuOptionWidget( {
720 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
721 data
: new OO
.ui
.FieldLayout(
722 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
723 classes
: [ 'mw-apisandbox-textInputCode' ],
727 value
: JSON
.stringify( displayParams
, null, '\t' )
729 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
731 ).on( 'toggle', function ( visible
) {
733 // Call updatePosition instead of adjustSize
734 // because the latter has weird caching
735 // behavior and the former bypasses it.
736 jsonInput
.updatePosition();
742 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
748 * Event handler for when formatDropdown's selection changes
750 onFormatDropdownChange: function () {
752 menu
= formatDropdown
.getMenu(),
753 items
= menu
.getItems(),
754 selectedField
= menu
.findSelectedItem() ? menu
.findSelectedItem().getData() : null;
756 for ( i
= 0; i
< items
.length
; i
++ ) {
757 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
763 * Interface to ApiSandbox UI
765 * @class mw.special.ApiSandbox
771 * Automatically called on $.ready()
776 ApiSandbox
.isFullscreen
= false;
778 $content
= $( '#mw-apisandbox' );
780 windowManager
= new OO
.ui
.WindowManager();
781 $( 'body' ).append( windowManager
.$element
);
782 windowManager
.addWindows( {
783 errorAlert
: new OO
.ui
.MessageDialog()
786 fullscreenButton
= new OO
.ui
.ButtonWidget( {
787 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
788 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
789 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
791 $toolbar
= $( '<div>' )
792 .addClass( 'mw-apisandbox-toolbar' )
794 fullscreenButton
.$element
,
795 new OO
.ui
.ButtonWidget( {
796 label
: mw
.message( 'apisandbox-submit' ).text(),
797 flags
: [ 'primary', 'progressive' ]
798 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
799 new OO
.ui
.ButtonWidget( {
800 label
: mw
.message( 'apisandbox-reset' ).text(),
802 } ).on( 'click', ApiSandbox
.resetUI
).$element
805 booklet
= new OO
.ui
.BookletLayout( {
810 panel
= new OO
.ui
.PanelLayout( {
811 classes
: [ 'mw-apisandbox-container' ],
812 content
: [ booklet
],
817 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
819 // Parse the current hash string
820 if ( !ApiSandbox
.loadFromHash() ) {
821 ApiSandbox
.updateUI();
824 // If the hashchange event exists, use it. Otherwise, fake it.
825 // And, of course, IE has to be dumb.
826 if ( 'onhashchange' in window
&&
827 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
829 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
831 setInterval( function () {
832 if ( oldhash
!== location
.hash
) {
833 ApiSandbox
.loadFromHash();
840 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
842 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
844 .append( panel
.$element
)
847 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
849 ApiSandbox
.resizePanel();
853 * Toggle "fullscreen" mode
855 toggleFullscreen: function () {
856 var $body
= $( document
.body
),
857 $ui
= $( '#mw-apisandbox-ui' );
859 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
861 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
862 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
863 if ( ApiSandbox
.isFullscreen
) {
864 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
865 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
866 OO
.ui
.getDefaultOverlay().prepend( $ui
);
868 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
869 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
870 $content
.append( $ui
);
872 ApiSandbox
.resizePanel();
876 * Set the height of the panel based on the current viewport.
878 resizePanel: function () {
879 var height
= $( window
).height(),
880 contentTop
= $content
.offset().top
;
882 if ( ApiSandbox
.isFullscreen
) {
883 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
884 panel
.$element
.height( height
- 1 );
886 // Subtract the height of the intro text
887 height
-= panel
.$element
.offset().top
- contentTop
;
889 panel
.$element
.height( height
- 10 );
890 $( window
).scrollTop( contentTop
- 5 );
895 * Update the current query when the page hash changes
897 * @return {boolean} Successful
899 loadFromHash: function () {
901 hash
= location
.hash
;
903 if ( oldhash
=== hash
) {
911 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
913 hash
= hash
.replace( /\+/g, '%20' );
914 re
= /([^&=#]+)=?([^&#]*)/g;
915 while ( ( m
= re
.exec( hash
) ) ) {
916 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
919 ApiSandbox
.updateUI( params
);
924 * Update the pages in the booklet
926 * @param {Object} [params] Optional query parameters to load
928 updateUI: function ( params
) {
929 var i
, page
, subpages
, j
, removePages
,
932 if ( !$.isPlainObject( params
) ) {
936 if ( updatingBooklet
) {
939 updatingBooklet
= true;
941 if ( params
!== undefined ) {
942 pages
.main
.loadQueryParams( params
);
944 addPages
.push( pages
.main
);
945 if ( resultPage
!== null ) {
946 addPages
.push( resultPage
);
948 pages
.main
.apiCheckValid();
951 while ( addPages
.length
) {
952 page
= addPages
.shift();
953 if ( bookletPages
[ i
] !== page
) {
954 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
955 if ( bookletPages
[ j
].getName() === page
.getName() ) {
956 bookletPages
.splice( j
, 1 );
959 bookletPages
.splice( i
, 0, page
);
960 booklet
.addPages( [ page
], i
);
964 if ( page
.getSubpages
) {
965 subpages
= page
.getSubpages();
966 for ( j
= 0; j
< subpages
.length
; j
++ ) {
967 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
968 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
969 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
971 if ( params
!== undefined ) {
972 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
974 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
975 pages
[ subpages
[ j
].key
].apiCheckValid();
980 if ( bookletPages
.length
> i
) {
981 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
982 booklet
.removePages( removePages
);
985 if ( !booklet
.getCurrentPageName() ) {
986 booklet
.selectFirstSelectablePage();
989 updatingBooklet
= false;
994 * Reset button handler
996 resetUI: function () {
997 suppressErrors
= true;
999 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
1002 ApiSandbox
.updateUI();
1006 * Submit button handler
1008 * @param {Object} [params] Use this set of params instead of those in the form fields.
1009 * The form fields will be updated to match.
1011 sendRequest: function ( params
) {
1012 var page
, subpages
, i
, query
, $result
, $focus
,
1013 progress
, $progressText
, progressLoading
,
1015 paramsAreForced
= !!params
,
1017 checkPages
= [ pages
.main
];
1019 // Blur any focused widget before submit, because
1020 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
1021 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
1022 if ( $focus
.length
) {
1026 suppressErrors
= false;
1028 // save widget state in params (or load from it if we are forced)
1029 if ( paramsAreForced
) {
1030 ApiSandbox
.updateUI( params
);
1033 while ( checkPages
.length
) {
1034 page
= checkPages
.shift();
1035 deferreds
.push( page
.apiCheckValid() );
1036 page
.getQueryParams( params
, displayParams
);
1037 subpages
= page
.getSubpages();
1038 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1039 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1040 checkPages
.push( pages
[ subpages
[ i
].key
] );
1045 if ( !paramsAreForced
) {
1046 // forced params means we are continuing a query; the base query should be preserved
1047 baseRequestParams
= $.extend( {}, params
);
1050 $.when
.apply( $, deferreds
).done( function () {
1051 var formatItems
, menu
, selectedLabel
;
1053 if ( $.inArray( false, arguments
) !== -1 ) {
1054 windowManager
.openWindow( 'errorAlert', {
1055 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1056 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1060 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1068 query
= $.param( displayParams
);
1070 formatItems
= Util
.formatRequest( displayParams
, params
);
1072 // Force a 'fm' format with wrappedhtml=1, if available
1073 if ( params
.format
!== undefined ) {
1074 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1075 params
.format
= params
.format
+ 'fm';
1077 if ( params
.format
.substr( -2 ) === 'fm' ) {
1078 params
.wrappedhtml
= 1;
1082 progressLoading
= false;
1083 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1084 progress
= new OO
.ui
.ProgressBarWidget( {
1086 $content
: $progressText
1089 $result
= $( '<div>' )
1090 .append( progress
.$element
);
1092 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1093 page
.setupOutlineItem = function () {
1094 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1097 if ( !formatDropdown
) {
1098 formatDropdown
= new OO
.ui
.DropdownWidget( {
1099 menu
: { items
: [] },
1102 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1105 menu
= formatDropdown
.getMenu();
1106 selectedLabel
= menu
.findSelectedItem() ? menu
.findSelectedItem().getLabel() : '';
1107 if ( typeof selectedLabel
!== 'string' ) {
1108 selectedLabel
= selectedLabel
.text();
1110 menu
.clearItems().addItems( formatItems
);
1111 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1113 // Fire the event to update field visibilities
1114 Util
.onFormatDropdownChange();
1116 page
.$element
.empty()
1118 new OO
.ui
.FieldLayout(
1120 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1123 formatItems
.map( function ( item
) {
1124 return item
.getData().$element
;
1128 ApiSandbox
.updateUI();
1129 booklet
.setPage( '|results|' );
1131 location
.href
= oldhash
= '#' + query
;
1134 contentType
: 'multipart/form-data',
1137 var xhr
= new window
.XMLHttpRequest();
1138 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1139 if ( !progressLoading
) {
1140 if ( e
.lengthComputable
) {
1141 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1143 progress
.setProgress( false );
1147 xhr
.addEventListener( 'progress', function ( e
) {
1148 if ( !progressLoading
) {
1149 progressLoading
= true;
1150 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1152 if ( e
.lengthComputable
) {
1153 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1155 progress
.setProgress( false );
1161 .catch( function ( code
, data
, result
, jqXHR
) {
1162 var deferred
= $.Deferred();
1164 if ( code
!== 'http' ) {
1165 // Not really an error, work around mw.Api thinking it is.
1166 deferred
.resolve( result
, jqXHR
);
1169 deferred
.reject
.apply( deferred
, arguments
);
1171 return deferred
.promise();
1173 .then( function ( data
, jqXHR
) {
1174 var m
, loadTime
, button
, clear
,
1175 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1176 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1179 if ( loginSuppressed
!== 'false' ) {
1181 .addClass( 'warning' )
1182 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1183 .appendTo( $result
);
1185 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1186 data
= JSON
.parse( data
);
1187 if ( data
.modules
.length
) {
1188 mw
.loader
.load( data
.modules
);
1190 if ( data
.status
&& data
.status
!== 200 ) {
1192 .addClass( 'api-pretty-header api-pretty-status' )
1193 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1194 .appendTo( $result
);
1196 $result
.append( Util
.parseHTML( data
.html
) );
1197 loadTime
= data
.time
;
1198 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1199 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1200 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1201 loadTime
= parseInt( m
[ 1 ], 10 );
1205 .addClass( 'api-pretty-content' )
1207 .appendTo( $result
);
1209 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1211 $( '<div>' ).append(
1212 new OO
.ui
.ButtonWidget( {
1213 label
: mw
.message( 'apisandbox-continue' ).text()
1214 } ).on( 'click', function () {
1215 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1216 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1217 ( clear
= new OO
.ui
.ButtonWidget( {
1218 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1219 } ).on( 'click', function () {
1220 ApiSandbox
.updateUI( baseRequestParams
);
1221 clear
.setDisabled( true );
1222 booklet
.setPage( '|results|' );
1223 } ).setDisabled( !paramsAreForced
) ).$element
,
1224 new OO
.ui
.PopupButtonWidget( {
1229 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1237 if ( typeof loadTime
=== 'number' ) {
1239 $( '<div>' ).append(
1240 new OO
.ui
.LabelWidget( {
1241 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1247 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1248 // Flush all saved tokens in case one of them is the bad one.
1249 Util
.markTokensBad();
1250 button
= new OO
.ui
.ButtonWidget( {
1251 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1253 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1254 .on( 'click', button
.setDisabled
, [ true ], button
)
1255 .$element
.appendTo( $result
);
1257 }, function ( code
, data
) {
1258 var details
= 'HTTP error: ' + data
.exception
;
1261 new OO
.ui
.LabelWidget( {
1262 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1263 classes
: [ 'error' ]
1271 * Handler for the "Correct token and resubmit" button
1273 * Used on a 'badtoken' error, it re-fetches token parameters for all
1274 * pages and then re-submits the query.
1276 fixTokenAndResend: function () {
1277 var page
, subpages
, i
, k
,
1279 tokenWait
= { dummy
: true },
1280 checkPages
= [ pages
.main
],
1281 success = function ( k
) {
1282 delete tokenWait
[ k
];
1283 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1284 ApiSandbox
.sendRequest();
1287 failure = function ( k
) {
1288 delete tokenWait
[ k
];
1292 while ( checkPages
.length
) {
1293 page
= checkPages
.shift();
1295 if ( page
.tokenWidget
) {
1296 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1297 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1299 .done( success
.bind( page
.tokenWidget
, k
) )
1300 .fail( failure
.bind( page
.tokenWidget
, k
) );
1303 subpages
= page
.getSubpages();
1304 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1305 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1306 checkPages
.push( pages
[ subpages
[ i
].key
] );
1311 success( 'dummy', '' );
1315 * Reset validity indicators for all widgets
1317 updateValidityIndicators: function () {
1318 var page
, subpages
, i
,
1319 checkPages
= [ pages
.main
];
1321 while ( checkPages
.length
) {
1322 page
= checkPages
.shift();
1323 page
.apiCheckValid();
1324 subpages
= page
.getSubpages();
1325 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1326 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1327 checkPages
.push( pages
[ subpages
[ i
].key
] );
1335 * PageLayout for API modules
1339 * @extends OO.ui.PageLayout
1341 * @param {Object} [config] Configuration options
1343 ApiSandbox
.PageLayout = function ( config
) {
1344 config
= $.extend( { prefix
: '' }, config
);
1345 this.displayText
= config
.key
;
1346 this.apiModule
= config
.path
;
1347 this.prefix
= config
.prefix
;
1348 this.paramInfo
= null;
1349 this.apiIsValid
= true;
1350 this.loadFromQueryParams
= null;
1352 this.tokenWidget
= null;
1353 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1354 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1355 this.loadParamInfo();
1357 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1358 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1359 this.outlineItem
.setLevel( this.indentLevel
);
1360 this.outlineItem
.setLabel( this.displayText
);
1361 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1362 this.outlineItem
.setIconTitle(
1363 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1368 * Fetch module information for this page's module, then create UI
1370 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1371 var dynamicFieldset
, dynamicParamNameWidget
,
1373 removeDynamicParamWidget = function ( name
, layout
) {
1374 dynamicFieldset
.removeItems( [ layout
] );
1375 delete that
.widgets
[ name
];
1377 addDynamicParamWidget = function () {
1378 var name
, layout
, widget
, button
;
1380 // Check name is filled in
1381 name
= dynamicParamNameWidget
.getValue().trim();
1382 if ( name
=== '' ) {
1383 dynamicParamNameWidget
.focus();
1387 if ( that
.widgets
[ name
] !== undefined ) {
1388 windowManager
.openWindow( 'errorAlert', {
1389 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1393 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1401 widget
= Util
.createWidgetForParameter( {
1408 button
= new OO
.ui
.ButtonWidget( {
1410 flags
: 'destructive'
1412 layout
= new OO
.ui
.ActionFieldLayout(
1420 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1421 that
.widgets
[ name
] = widget
;
1422 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1425 dynamicParamNameWidget
.setValue( '' );
1428 this.$element
.empty()
1429 .append( new OO
.ui
.ProgressBarWidget( {
1431 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1434 Util
.fetchModuleInfo( this.apiModule
)
1435 .done( function ( pi
) {
1436 var prefix
, i
, j
, descriptionContainer
, widget
, layoutConfig
, button
, widgetField
, helpField
, tmp
, flag
, count
,
1438 deprecatedItems
= [],
1440 filterFmModules = function ( v
) {
1441 return v
.substr( -2 ) !== 'fm' ||
1442 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1444 widgetLabelOnClick = function () {
1445 var f
= this.getField();
1446 if ( $.isFunction( f
.setDisabled
) ) {
1447 f
.setDisabled( false );
1449 if ( $.isFunction( f
.focus
) ) {
1454 // This is something of a hack. We always want the 'format' and
1455 // 'action' parameters from the main module to be specified,
1456 // and for 'format' we also want to simplify the dropdown since
1457 // we always send the 'fm' variant.
1458 if ( that
.apiModule
=== 'main' ) {
1459 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1460 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1461 pi
.parameters
[ i
].required
= true;
1462 delete pi
.parameters
[ i
][ 'default' ];
1464 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1465 tmp
= pi
.parameters
[ i
].type
;
1466 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1467 availableFormats
[ tmp
[ j
] ] = true;
1469 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1470 pi
.parameters
[ i
][ 'default' ] = 'json';
1471 pi
.parameters
[ i
].required
= true;
1476 // Hide the 'wrappedhtml' parameter on format modules
1477 if ( pi
.group
=== 'format' ) {
1478 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1479 return p
.name
!== 'wrappedhtml';
1483 that
.paramInfo
= pi
;
1485 items
.push( new OO
.ui
.FieldLayout(
1486 new OO
.ui
.Widget( {} ).toggle( false ), {
1488 label
: Util
.parseHTML( pi
.description
)
1492 if ( pi
.helpurls
.length
) {
1493 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1495 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1500 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1501 return $( '<li>' ).append( $( '<a>' )
1502 .attr( { href
: link
, target
: '_blank' } )
1510 if ( pi
.examples
.length
) {
1511 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1513 label
: mw
.message( 'apisandbox-examples' ).text(),
1518 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1520 .attr( 'href', '#' + example
.query
)
1521 .html( example
.description
);
1522 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1523 return $( '<li>' ).append( a
);
1529 if ( buttons
.length
) {
1530 items
.push( new OO
.ui
.FieldLayout(
1531 new OO
.ui
.ButtonGroupWidget( {
1533 } ), { align
: 'top' }
1537 if ( pi
.parameters
.length
) {
1538 prefix
= that
.prefix
+ pi
.prefix
;
1539 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1540 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1541 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1542 if ( pi
.parameters
[ i
].tokentype
) {
1543 that
.tokenWidget
= widget
;
1546 descriptionContainer
= $( '<div>' );
1548 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1549 tmp
.filter( 'dl' ).makeCollapsible( {
1551 } ).children( '.mw-collapsible-toggle' ).each( function () {
1552 var $this = $( this );
1553 $this.parent().prev( 'p' ).append( $this );
1555 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1557 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1558 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1559 descriptionContainer
.append( $( '<div>' )
1561 .append( Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] ) )
1567 switch ( pi
.parameters
[ i
].type
) {
1570 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1574 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1575 descriptionContainer
.append( $( '<div>' )
1579 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1582 Util
.parseMsg( 'apisandbox-param-limit' )
1586 descriptionContainer
.append( $( '<div>' )
1589 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1591 Util
.parseMsg( 'apisandbox-param-limit' )
1599 if ( pi
.parameters
[ i
].min
!== undefined ) {
1602 if ( pi
.parameters
[ i
].max
!== undefined ) {
1606 descriptionContainer
.append( $( '<div>' )
1608 .append( Util
.parseMsg(
1609 'api-help-param-integer-' + tmp
,
1610 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1611 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1618 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1620 count
= pi
.parameters
[ i
].type
.length
;
1624 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1626 if ( flag
&& !( widget
instanceof OO
.ui
.TagMultiselectWidget
) &&
1628 widget
instanceof OptionalWidget
&&
1629 widget
.widget
instanceof OO
.ui
.TagMultiselectWidget
1632 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1634 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1636 mw
.message( 'api-help-param-multi-max',
1637 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1642 descriptionContainer
.append( $( '<div>' )
1644 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1648 if ( 'maxbytes' in pi
.parameters
[ i
] ) {
1649 descriptionContainer
.append( $( '<div>' )
1651 .append( Util
.parseMsg( 'api-help-param-maxbytes', pi
.parameters
[ i
].maxbytes
) )
1654 if ( 'maxchars' in pi
.parameters
[ i
] ) {
1655 descriptionContainer
.append( $( '<div>' )
1657 .append( Util
.parseMsg( 'api-help-param-maxchars', pi
.parameters
[ i
].maxchars
) )
1660 helpField
= new OO
.ui
.FieldLayout(
1663 classes
: [ 'mw-apisandbox-spacer' ]
1666 classes
: [ 'mw-apisandbox-help-field' ],
1667 label
: descriptionContainer
1673 classes
: [ 'mw-apisandbox-widget-field' ],
1674 label
: prefix
+ pi
.parameters
[ i
].name
1677 if ( pi
.parameters
[ i
].tokentype
) {
1678 button
= new OO
.ui
.ButtonWidget( {
1679 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1681 button
.on( 'click', widget
.fetchToken
, [], widget
);
1683 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1685 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1688 // We need our own click handler on the widget label to
1689 // turn off the disablement.
1690 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1692 // Don't grey out the label when the field is disabled,
1693 // it makes it too hard to read and our "disabled"
1694 // isn't really disabled.
1695 widgetField
.onFieldDisable( false );
1696 widgetField
.onFieldDisable
= $.noop
;
1698 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1699 deprecatedItems
.push( widgetField
, helpField
);
1701 items
.push( widgetField
, helpField
);
1706 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1707 items
.push( new OO
.ui
.FieldLayout(
1708 new OO
.ui
.Widget( {} ).toggle( false ), {
1710 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1715 that
.$element
.empty();
1717 new OO
.ui
.FieldsetLayout( {
1718 label
: that
.displayText
1719 } ).addItems( items
)
1720 .$element
.appendTo( that
.$element
);
1722 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1723 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1724 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1725 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1726 } ).on( 'enter', addDynamicParamWidget
);
1727 dynamicFieldset
.addItems( [
1728 new OO
.ui
.FieldLayout(
1729 new OO
.ui
.Widget( {} ).toggle( false ), {
1731 label
: Util
.parseHTML( pi
.dynamicparameters
)
1734 new OO
.ui
.ActionFieldLayout(
1735 dynamicParamNameWidget
,
1736 new OO
.ui
.ButtonWidget( {
1738 flags
: 'progressive'
1739 } ).on( 'click', addDynamicParamWidget
),
1741 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1748 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1749 dynamicFieldset
.$element
1751 .appendTo( that
.$element
);
1754 if ( deprecatedItems
.length
) {
1755 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1758 $( '<legend>' ).append(
1759 new OO
.ui
.ToggleButtonWidget( {
1760 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1761 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1765 .appendTo( that
.$element
);
1768 // Load stored params, if any, then update the booklet if we
1769 // have subpages (or else just update our valid-indicator).
1770 tmp
= that
.loadFromQueryParams
;
1771 that
.loadFromQueryParams
= null;
1772 if ( $.isPlainObject( tmp
) ) {
1773 that
.loadQueryParams( tmp
);
1775 if ( that
.getSubpages().length
> 0 ) {
1776 ApiSandbox
.updateUI( tmp
);
1778 that
.apiCheckValid();
1780 } ).fail( function ( code
, detail
) {
1781 that
.$element
.empty()
1783 new OO
.ui
.LabelWidget( {
1784 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1785 classes
: [ 'error' ]
1787 new OO
.ui
.ButtonWidget( {
1788 label
: mw
.message( 'apisandbox-retry' ).text()
1789 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1795 * Check that all widgets on the page are in a valid state.
1799 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1802 if ( this.paramInfo
=== null ) {
1803 return $.Deferred().resolve( false ).promise();
1805 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1806 return widget
.apiCheckValid();
1807 } ) ).then( function () {
1808 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1809 if ( that
.getOutlineItem() ) {
1810 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1811 that
.getOutlineItem().setIconTitle(
1812 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1815 return $.Deferred().resolve( that
.apiIsValid
).promise();
1821 * Load form fields from query parameters
1823 * @param {Object} params
1825 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1826 if ( this.paramInfo
=== null ) {
1827 this.loadFromQueryParams
= params
;
1829 $.each( this.widgets
, function ( name
, widget
) {
1830 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1831 widget
.setApiValue( v
);
1837 * Load query params from form fields
1839 * @param {Object} params Write query parameters into this object
1840 * @param {Object} displayParams Write query parameters for display into this object
1842 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1843 $.each( this.widgets
, function ( name
, widget
) {
1844 var value
= widget
.getApiValue();
1845 if ( value
!== undefined ) {
1846 params
[ name
] = value
;
1847 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1848 value
= widget
.getApiValueForDisplay();
1850 displayParams
[ name
] = value
;
1856 * Fetch a list of subpage names loaded by this page
1860 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1862 $.each( this.widgets
, function ( name
, widget
) {
1864 if ( $.isFunction( widget
.getSubmodules
) ) {
1865 submodules
= widget
.getSubmodules();
1866 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1868 key
: name
+ '=' + submodules
[ i
].value
,
1869 path
: submodules
[ i
].path
,
1870 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1878 $( ApiSandbox
.init
);
1880 module
.exports
= ApiSandbox
;
1882 }( jQuery
, mediaWiki
, OO
) );