1 /* eslint-disable no-use-before-define */
2 ( function ( $, mw
, OO
) {
4 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
5 $content
, panel
, booklet
, oldhash
, windowManager
, fullscreenButton
,
11 suppressErrors
= true,
12 updatingBooklet
= false,
19 getApiValue: function () {
20 return this.getValue();
22 setApiValue: function ( v
) {
23 if ( v
=== undefined ) {
24 v
= this.paramInfo
[ 'default' ];
28 apiCheckValid: function () {
30 return this.getValidity().then( function () {
31 return $.Deferred().resolve( true ).promise();
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() );
42 dateTimeInputWidget
: {
43 getValidity: function () {
44 if ( !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '' ) {
45 return $.Deferred().resolve().promise();
47 return $.Deferred().reject().promise();
53 alertTokenError: function ( code
, error
) {
54 windowManager
.openWindow( 'errorAlert', {
55 title
: Util
.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo
.tokentype
),
60 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
66 fetchToken: function () {
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 ) );
73 setApiValue: function ( v
) {
74 WidgetMethods
.textInputWidget
.setApiValue
.call( this, v
);
75 if ( v
=== '123ABC' ) {
82 getApiValueForDisplay: function () {
88 getApiValue: function () {
89 return this.getValue() ? 1 : undefined;
91 setApiValue: function ( v
) {
92 this.setValue( Util
.apiBool( v
) );
94 apiCheckValid: function () {
95 return $.Deferred().resolve( true ).promise();
100 getApiValue: function () {
101 var item
= this.getMenu().getSelectedItem();
102 return item
=== null ? undefined : item
.getData();
104 setApiValue: function ( v
) {
105 var menu
= this.getMenu();
107 if ( v
=== undefined ) {
108 v
= this.paramInfo
[ 'default' ];
110 if ( v
=== undefined ) {
113 menu
.selectItemByData( String( v
) );
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();
125 getApiValue: function () {
126 var items
= this.getItemsData();
127 if ( items
.join( '' ).indexOf( '|' ) === -1 ) {
128 return items
.join( '|' );
130 return '\x1f' + items
.join( '\x1f' );
133 setApiValue: function ( v
) {
134 if ( v
=== undefined || v
=== '' || v
=== '\x1f' ) {
135 this.setItemsFromData( [] );
138 if ( v
.indexOf( '\x1f' ) !== 0 ) {
139 this.setItemsFromData( v
.split( '|' ) );
141 this.setItemsFromData( v
.substr( 1 ).split( '\x1f' ) );
145 apiCheckValid: function () {
149 if ( !suppressErrors
) {
150 ok
= this.getApiValue() !== undefined && !(
151 pi
.allspecifier
!== undefined &&
152 this.getItemsData().length
> 1 &&
153 this.getItemsData().indexOf( pi
.allspecifier
) !== -1
157 this.setIcon( ok
? null : 'alert' );
158 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
159 return $.Deferred().resolve( ok
).promise();
161 createItemWidget: function ( data
, label
) {
162 var item
= OO
.ui
.CapsuleMultiselectWidget
.prototype.createItemWidget
.call( this, data
, label
);
163 if ( this.paramInfo
.deprecatedvalues
&&
164 this.paramInfo
.deprecatedvalues
.indexOf( data
) >= 0
166 item
.$element
.addClass( 'apihelp-deprecated-value' );
173 getApiValue: function () {
174 return this.isDisabled() ? undefined : this.widget
.getApiValue();
176 setApiValue: function ( v
) {
177 this.setDisabled( v
=== undefined );
178 this.widget
.setApiValue( v
);
180 apiCheckValid: function () {
181 if ( this.isDisabled() ) {
182 return $.Deferred().resolve( true ).promise();
184 return this.widget
.apiCheckValid();
190 single: function () {
191 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
192 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
195 var map
= this.paramInfo
.submodules
,
196 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
197 return v
=== undefined || v
=== '' ? [] : String( v
).split( '|' ).map( function ( v
) {
198 return { value
: v
, path
: map
[ v
] };
204 getApiValueForDisplay: function () {
207 getApiValue: function () {
208 return this.getValue();
210 setApiValue: function () {
213 apiCheckValid: function () {
214 var ok
= this.getValue() !== null || suppressErrors
;
215 this.setIcon( ok
? null : 'alert' );
216 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
217 return $.Deferred().resolve( ok
).promise();
223 generic: function () {
224 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
229 * @class mw.special.ApiSandbox.Util
234 * Fetch API module info
236 * @param {string} module Module to fetch data for
237 * @return {jQuery.Promise}
239 fetchModuleInfo: function ( module
) {
241 deferred
= $.Deferred();
243 if ( moduleInfoCache
.hasOwnProperty( module
) ) {
245 .resolve( moduleInfoCache
[ module
] )
246 .promise( { abort: function () {} } );
248 apiPromise
= api
.post( {
252 uselang
: mw
.config
.get( 'wgUserLanguage' )
253 } ).done( function ( data
) {
256 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
257 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
261 info
= data
.paraminfo
.modules
;
262 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
263 deferred
.reject( '???', 'No module data returned' );
267 moduleInfoCache
[ module
] = info
[ 0 ];
268 deferred
.resolve( info
[ 0 ] );
269 } ).fail( function ( code
, details
) {
270 if ( code
=== 'http' ) {
271 details
= 'HTTP error: ' + details
.exception
;
272 } else if ( details
.error
) {
273 details
= details
.error
.info
;
275 deferred
.reject( code
, details
);
278 .promise( { abort
: apiPromise
.abort
} );
283 * Mark all currently-in-use tokens as bad
285 markTokensBad: function () {
286 var page
, subpages
, i
,
287 checkPages
= [ pages
.main
];
289 while ( checkPages
.length
) {
290 page
= checkPages
.shift();
292 if ( page
.tokenWidget
) {
293 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
296 subpages
= page
.getSubpages();
297 for ( i
= 0; i
< subpages
.length
; i
++ ) {
298 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
299 checkPages
.push( pages
[ subpages
[ i
].key
] );
306 * Test an API boolean
308 * @param {Mixed} value
311 apiBool: function ( value
) {
312 return value
!== undefined && value
!== false;
316 * Create a widget for a parameter.
318 * @param {Object} pi Parameter info from API
319 * @param {Object} opts Additional options
320 * @return {OO.ui.Widget}
322 createWidgetForParameter: function ( pi
, opts
) {
323 var widget
, innerWidget
, finalWidget
, items
, $button
, $content
, func
,
330 widget
= new OO
.ui
.ToggleSwitchWidget();
331 widget
.paramInfo
= pi
;
332 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
333 pi
.required
= true; // Avoid wrapping in the non-required widget
338 if ( Util
.apiBool( pi
.multi
) ) {
339 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
340 allowArbitrary
: true,
341 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
344 widget
.paramInfo
= pi
;
345 $.extend( widget
, WidgetMethods
.capsuleWidget
);
347 widget
= new OO
.ui
.TextInputWidget( {
348 required
: Util
.apiBool( pi
.required
)
351 if ( !Util
.apiBool( pi
.multi
) ) {
352 widget
.paramInfo
= pi
;
353 $.extend( widget
, WidgetMethods
.textInputWidget
);
354 widget
.setValidation( Validators
.generic
);
356 if ( pi
.tokentype
) {
357 widget
.paramInfo
= pi
;
358 $.extend( widget
, WidgetMethods
.textInputWidget
);
359 $.extend( widget
, WidgetMethods
.tokenWidget
);
364 widget
= new OO
.ui
.MultilineTextInputWidget( {
365 required
: Util
.apiBool( pi
.required
)
367 widget
.paramInfo
= pi
;
368 $.extend( widget
, WidgetMethods
.textInputWidget
);
369 widget
.setValidation( Validators
.generic
);
373 widget
= new OO
.ui
.TextInputWidget( {
375 required
: Util
.apiBool( pi
.required
)
377 widget
.paramInfo
= pi
;
378 $.extend( widget
, WidgetMethods
.textInputWidget
);
379 $.extend( widget
, WidgetMethods
.passwordWidget
);
380 widget
.setValidation( Validators
.generic
);
385 widget
= new OO
.ui
.NumberInputWidget( {
386 required
: Util
.apiBool( pi
.required
),
389 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
390 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
391 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
392 widget
.paramInfo
= pi
;
393 $.extend( widget
, WidgetMethods
.textInputWidget
);
394 if ( Util
.apiBool( pi
.enforcerange
) ) {
395 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
401 widget
= new OO
.ui
.TextInputWidget( {
402 required
: Util
.apiBool( pi
.required
)
404 widget
.setValidation( function ( value
) {
405 var n
, pi
= this.paramInfo
;
407 if ( value
=== 'max' ) {
411 return !isNaN( n
) && isFinite( n
) &&
412 Math
.floor( n
) === n
&&
413 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
416 pi
.min
= pi
.min
|| 0;
417 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
418 widget
.paramInfo
= pi
;
419 $.extend( widget
, WidgetMethods
.textInputWidget
);
424 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
426 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
428 required
: Util
.apiBool( pi
.required
),
431 widget
.paramInfo
= pi
;
432 $.extend( widget
, WidgetMethods
.textInputWidget
);
433 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
434 multiMode
= 'indicator';
438 widget
= new OO
.ui
.SelectFileWidget();
439 widget
.paramInfo
= pi
;
440 $.extend( widget
, WidgetMethods
.uploadWidget
);
444 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
446 name
= mw
.message( 'blanknamespace' ).text();
448 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
449 } ).sort( function ( a
, b
) {
450 return a
.data
- b
.data
;
452 if ( Util
.apiBool( pi
.multi
) ) {
453 if ( pi
.allspecifier
!== undefined ) {
454 items
.unshift( new OO
.ui
.MenuOptionWidget( {
455 data
: pi
.allspecifier
,
456 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
460 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
461 menu
: { items
: items
},
464 widget
.paramInfo
= pi
;
465 $.extend( widget
, WidgetMethods
.capsuleWidget
);
467 widget
= new OO
.ui
.DropdownWidget( {
468 menu
: { items
: items
},
471 widget
.paramInfo
= pi
;
472 $.extend( widget
, WidgetMethods
.dropdownWidget
);
477 if ( !Array
.isArray( pi
.type
) ) {
478 throw new Error( 'Unknown parameter type ' + pi
.type
);
481 items
= pi
.type
.map( function ( v
) {
487 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
488 config
.classes
.push( 'apihelp-deprecated-value' );
490 return new OO
.ui
.MenuOptionWidget( config
);
492 if ( Util
.apiBool( pi
.multi
) ) {
493 if ( pi
.allspecifier
!== undefined ) {
494 items
.unshift( new OO
.ui
.MenuOptionWidget( {
495 data
: pi
.allspecifier
,
496 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
500 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
501 menu
: { items
: items
},
504 widget
.paramInfo
= pi
;
505 $.extend( widget
, WidgetMethods
.capsuleWidget
);
506 if ( Util
.apiBool( pi
.submodules
) ) {
507 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
508 widget
.on( 'change', ApiSandbox
.updateUI
);
511 widget
= new OO
.ui
.DropdownWidget( {
512 menu
: { items
: items
},
515 widget
.paramInfo
= pi
;
516 $.extend( widget
, WidgetMethods
.dropdownWidget
);
517 if ( Util
.apiBool( pi
.submodules
) ) {
518 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
519 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
521 if ( pi
.deprecatedvalues
) {
522 widget
.getMenu().on( 'select', function ( item
) {
523 this.$element
.toggleClass(
524 'apihelp-deprecated-value',
525 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
534 if ( Util
.apiBool( pi
.multi
) && multiMode
!== 'none' ) {
535 innerWidget
= widget
;
536 switch ( multiMode
) {
538 $content
= innerWidget
.$element
;
542 $button
= innerWidget
.$indicator
;
543 $button
.css( 'cursor', 'pointer' );
544 $button
.attr( 'tabindex', 0 );
545 $button
.parent().append( $button
);
546 innerWidget
.setIndicator( 'next' );
547 $content
= innerWidget
.$element
;
551 throw new Error( 'Unknown multiMode "' + multiMode
+ '"' );
554 widget
= new OO
.ui
.CapsuleMultiselectWidget( {
555 allowArbitrary
: true,
556 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
559 classes
: [ 'mw-apisandbox-popup' ],
563 widget
.paramInfo
= pi
;
564 $.extend( widget
, WidgetMethods
.capsuleWidget
);
567 if ( !innerWidget
.isDisabled() ) {
568 innerWidget
.apiCheckValid().done( function ( ok
) {
570 widget
.addItemsFromData( [ innerWidget
.getApiValue() ] );
571 innerWidget
.setApiValue( undefined );
577 switch ( multiMode
) {
579 innerWidget
.connect( null, { enter
: func
} );
585 keypress: function ( e
) {
586 if ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) {
595 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
596 finalWidget
= widget
;
598 finalWidget
= new OptionalWidget( widget
);
599 finalWidget
.paramInfo
= pi
;
600 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
601 if ( widget
.getSubmodules
) {
602 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
603 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
605 finalWidget
.setDisabled( true );
608 widget
.setApiValue( pi
[ 'default' ] );
614 * Parse an HTML string and call Util.fixupHTML()
616 * @param {string} html HTML to parse
619 parseHTML: function ( html
) {
620 var $ret
= $( $.parseHTML( html
) );
621 return Util
.fixupHTML( $ret
);
625 * Parse an i18n message and call Util.fixupHTML()
627 * @param {string} key Key of message to get
628 * @param {...Mixed} parameters Values for $N replacements
631 parseMsg: function () {
632 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
633 return Util
.fixupHTML( $ret
);
637 * Fix HTML for ApiSandbox display
640 * - Add target="_blank" to any links
642 * @param {jQuery} $html DOM to process
645 fixupHTML: function ( $html
) {
646 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
647 .filter( '[href]:not([target])' )
648 .attr( 'target', '_blank' );
653 * Format a request and return a bunch of menu option widgets
655 * @param {Object} displayParams Query parameters, sanitized for display.
656 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
657 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
659 formatRequest: function ( displayParams
, rawParams
) {
662 new OO
.ui
.MenuOptionWidget( {
663 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
664 data
: new OO
.ui
.FieldLayout(
665 new OO
.ui
.TextInputWidget( {
667 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
669 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
673 new OO
.ui
.MenuOptionWidget( {
674 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
675 data
: new OO
.ui
.FieldLayout(
676 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
677 classes
: [ 'mw-apisandbox-textInputCode' ],
681 value
: JSON
.stringify( displayParams
, null, '\t' )
683 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
685 ).on( 'toggle', function ( visible
) {
687 // Call updatePosition instead of adjustSize
688 // because the latter has weird caching
689 // behavior and the former bypasses it.
690 jsonInput
.updatePosition();
696 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
702 * Event handler for when formatDropdown's selection changes
704 onFormatDropdownChange: function () {
706 menu
= formatDropdown
.getMenu(),
707 items
= menu
.getItems(),
708 selectedField
= menu
.getSelectedItem() ? menu
.getSelectedItem().getData() : null;
710 for ( i
= 0; i
< items
.length
; i
++ ) {
711 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
717 * Interface to ApiSandbox UI
719 * @class mw.special.ApiSandbox
725 * Automatically called on $.ready()
730 ApiSandbox
.isFullscreen
= false;
732 $content
= $( '#mw-apisandbox' );
734 windowManager
= new OO
.ui
.WindowManager();
735 $( 'body' ).append( windowManager
.$element
);
736 windowManager
.addWindows( {
737 errorAlert
: new OO
.ui
.MessageDialog()
740 fullscreenButton
= new OO
.ui
.ButtonWidget( {
741 label
: mw
.message( 'apisandbox-fullscreen' ).text(),
742 title
: mw
.message( 'apisandbox-fullscreen-tooltip' ).text()
743 } ).on( 'click', ApiSandbox
.toggleFullscreen
);
745 $toolbar
= $( '<div>' )
746 .addClass( 'mw-apisandbox-toolbar' )
748 fullscreenButton
.$element
,
749 new OO
.ui
.ButtonWidget( {
750 label
: mw
.message( 'apisandbox-submit' ).text(),
751 flags
: [ 'primary', 'progressive' ]
752 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
753 new OO
.ui
.ButtonWidget( {
754 label
: mw
.message( 'apisandbox-reset' ).text(),
756 } ).on( 'click', ApiSandbox
.resetUI
).$element
759 booklet
= new OO
.ui
.BookletLayout( {
764 panel
= new OO
.ui
.PanelLayout( {
765 classes
: [ 'mw-apisandbox-container' ],
766 content
: [ booklet
],
771 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
773 // Parse the current hash string
774 if ( !ApiSandbox
.loadFromHash() ) {
775 ApiSandbox
.updateUI();
778 // If the hashchange event exists, use it. Otherwise, fake it.
779 // And, of course, IE has to be dumb.
780 if ( 'onhashchange' in window
&&
781 ( document
.documentMode
=== undefined || document
.documentMode
>= 8 )
783 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
785 setInterval( function () {
786 if ( oldhash
!== location
.hash
) {
787 ApiSandbox
.loadFromHash();
794 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
796 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
798 .append( panel
.$element
)
801 $( window
).on( 'resize', ApiSandbox
.resizePanel
);
803 ApiSandbox
.resizePanel();
807 * Toggle "fullscreen" mode
809 toggleFullscreen: function () {
810 var $body
= $( document
.body
),
811 $ui
= $( '#mw-apisandbox-ui' );
813 ApiSandbox
.isFullscreen
= !ApiSandbox
.isFullscreen
;
815 $body
.toggleClass( 'mw-apisandbox-fullscreen', ApiSandbox
.isFullscreen
);
816 $ui
.toggleClass( 'mw-body-content', ApiSandbox
.isFullscreen
);
817 if ( ApiSandbox
.isFullscreen
) {
818 fullscreenButton
.setLabel( mw
.message( 'apisandbox-unfullscreen' ).text() );
819 fullscreenButton
.setTitle( mw
.message( 'apisandbox-unfullscreen-tooltip' ).text() );
820 OO
.ui
.getDefaultOverlay().prepend( $ui
);
822 fullscreenButton
.setLabel( mw
.message( 'apisandbox-fullscreen' ).text() );
823 fullscreenButton
.setTitle( mw
.message( 'apisandbox-fullscreen-tooltip' ).text() );
824 $content
.append( $ui
);
826 ApiSandbox
.resizePanel();
830 * Set the height of the panel based on the current viewport.
832 resizePanel: function () {
833 var height
= $( window
).height(),
834 contentTop
= $content
.offset().top
;
836 if ( ApiSandbox
.isFullscreen
) {
837 height
-= panel
.$element
.offset().top
- $( '#mw-apisandbox-ui' ).offset().top
;
838 panel
.$element
.height( height
- 1 );
840 // Subtract the height of the intro text
841 height
-= panel
.$element
.offset().top
- contentTop
;
843 panel
.$element
.height( height
- 10 );
844 $( window
).scrollTop( contentTop
- 5 );
849 * Update the current query when the page hash changes
851 * @return {boolean} Successful
853 loadFromHash: function () {
855 hash
= location
.hash
;
857 if ( oldhash
=== hash
) {
865 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
867 hash
= hash
.replace( /\+/g, '%20' );
868 re
= /([^&=#]+)=?([^&#]*)/g;
869 while ( ( m
= re
.exec( hash
) ) ) {
870 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
873 ApiSandbox
.updateUI( params
);
878 * Update the pages in the booklet
880 * @param {Object} [params] Optional query parameters to load
882 updateUI: function ( params
) {
883 var i
, page
, subpages
, j
, removePages
,
886 if ( !$.isPlainObject( params
) ) {
890 if ( updatingBooklet
) {
893 updatingBooklet
= true;
895 if ( params
!== undefined ) {
896 pages
.main
.loadQueryParams( params
);
898 addPages
.push( pages
.main
);
899 if ( resultPage
!== null ) {
900 addPages
.push( resultPage
);
902 pages
.main
.apiCheckValid();
905 while ( addPages
.length
) {
906 page
= addPages
.shift();
907 if ( bookletPages
[ i
] !== page
) {
908 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
909 if ( bookletPages
[ j
].getName() === page
.getName() ) {
910 bookletPages
.splice( j
, 1 );
913 bookletPages
.splice( i
, 0, page
);
914 booklet
.addPages( [ page
], i
);
918 if ( page
.getSubpages
) {
919 subpages
= page
.getSubpages();
920 for ( j
= 0; j
< subpages
.length
; j
++ ) {
921 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
922 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
923 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
925 if ( params
!== undefined ) {
926 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
928 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
929 pages
[ subpages
[ j
].key
].apiCheckValid();
934 if ( bookletPages
.length
> i
) {
935 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
936 booklet
.removePages( removePages
);
939 if ( !booklet
.getCurrentPageName() ) {
940 booklet
.selectFirstSelectablePage();
943 updatingBooklet
= false;
948 * Reset button handler
950 resetUI: function () {
951 suppressErrors
= true;
953 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
956 ApiSandbox
.updateUI();
960 * Submit button handler
962 * @param {Object} [params] Use this set of params instead of those in the form fields.
963 * The form fields will be updated to match.
965 sendRequest: function ( params
) {
966 var page
, subpages
, i
, query
, $result
, $focus
,
967 progress
, $progressText
, progressLoading
,
969 paramsAreForced
= !!params
,
971 checkPages
= [ pages
.main
];
973 // Blur any focused widget before submit, because
974 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
975 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
976 if ( $focus
.length
) {
980 suppressErrors
= false;
982 // save widget state in params (or load from it if we are forced)
983 if ( paramsAreForced
) {
984 ApiSandbox
.updateUI( params
);
987 while ( checkPages
.length
) {
988 page
= checkPages
.shift();
989 deferreds
.push( page
.apiCheckValid() );
990 page
.getQueryParams( params
, displayParams
);
991 subpages
= page
.getSubpages();
992 for ( i
= 0; i
< subpages
.length
; i
++ ) {
993 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
994 checkPages
.push( pages
[ subpages
[ i
].key
] );
999 if ( !paramsAreForced
) {
1000 // forced params means we are continuing a query; the base query should be preserved
1001 baseRequestParams
= $.extend( {}, params
);
1004 $.when
.apply( $, deferreds
).done( function () {
1005 var formatItems
, menu
, selectedLabel
;
1007 if ( $.inArray( false, arguments
) !== -1 ) {
1008 windowManager
.openWindow( 'errorAlert', {
1009 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1010 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1014 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1022 query
= $.param( displayParams
);
1024 formatItems
= Util
.formatRequest( displayParams
, params
);
1026 // Force a 'fm' format with wrappedhtml=1, if available
1027 if ( params
.format
!== undefined ) {
1028 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1029 params
.format
= params
.format
+ 'fm';
1031 if ( params
.format
.substr( -2 ) === 'fm' ) {
1032 params
.wrappedhtml
= 1;
1036 progressLoading
= false;
1037 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1038 progress
= new OO
.ui
.ProgressBarWidget( {
1040 $content
: $progressText
1043 $result
= $( '<div>' )
1044 .append( progress
.$element
);
1046 resultPage
= page
= new OO
.ui
.PageLayout( '|results|' );
1047 page
.setupOutlineItem = function () {
1048 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1051 if ( !formatDropdown
) {
1052 formatDropdown
= new OO
.ui
.DropdownWidget( {
1053 menu
: { items
: [] },
1056 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1059 menu
= formatDropdown
.getMenu();
1060 selectedLabel
= menu
.getSelectedItem() ? menu
.getSelectedItem().getLabel() : '';
1061 if ( typeof selectedLabel
!== 'string' ) {
1062 selectedLabel
= selectedLabel
.text();
1064 menu
.clearItems().addItems( formatItems
);
1065 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1067 // Fire the event to update field visibilities
1068 Util
.onFormatDropdownChange();
1070 page
.$element
.empty()
1072 new OO
.ui
.FieldLayout(
1074 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1077 formatItems
.map( function ( item
) {
1078 return item
.getData().$element
;
1082 ApiSandbox
.updateUI();
1083 booklet
.setPage( '|results|' );
1085 location
.href
= oldhash
= '#' + query
;
1088 contentType
: 'multipart/form-data',
1091 var xhr
= new window
.XMLHttpRequest();
1092 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1093 if ( !progressLoading
) {
1094 if ( e
.lengthComputable
) {
1095 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1097 progress
.setProgress( false );
1101 xhr
.addEventListener( 'progress', function ( e
) {
1102 if ( !progressLoading
) {
1103 progressLoading
= true;
1104 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1106 if ( e
.lengthComputable
) {
1107 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1109 progress
.setProgress( false );
1115 .catch( function ( code
, data
, result
, jqXHR
) {
1116 var deferred
= $.Deferred();
1118 if ( code
!== 'http' ) {
1119 // Not really an error, work around mw.Api thinking it is.
1120 deferred
.resolve( result
, jqXHR
);
1123 deferred
.reject
.apply( deferred
, arguments
);
1125 return deferred
.promise();
1127 .then( function ( data
, jqXHR
) {
1128 var m
, loadTime
, button
, clear
,
1129 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1130 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1133 if ( loginSuppressed
!== 'false' ) {
1135 .addClass( 'warning' )
1136 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1137 .appendTo( $result
);
1139 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1140 data
= JSON
.parse( data
);
1141 if ( data
.modules
.length
) {
1142 mw
.loader
.load( data
.modules
);
1144 if ( data
.status
&& data
.status
!== 200 ) {
1146 .addClass( 'api-pretty-header api-pretty-status' )
1147 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1148 .appendTo( $result
);
1150 $result
.append( Util
.parseHTML( data
.html
) );
1151 loadTime
= data
.time
;
1152 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1153 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1154 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1155 loadTime
= parseInt( m
[ 1 ], 10 );
1159 .addClass( 'api-pretty-content' )
1161 .appendTo( $result
);
1163 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1165 $( '<div>' ).append(
1166 new OO
.ui
.ButtonWidget( {
1167 label
: mw
.message( 'apisandbox-continue' ).text()
1168 } ).on( 'click', function () {
1169 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1170 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1171 ( clear
= new OO
.ui
.ButtonWidget( {
1172 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1173 } ).on( 'click', function () {
1174 ApiSandbox
.updateUI( baseRequestParams
);
1175 clear
.setDisabled( true );
1176 booklet
.setPage( '|results|' );
1177 } ).setDisabled( !paramsAreForced
) ).$element
,
1178 new OO
.ui
.PopupButtonWidget( {
1183 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1191 if ( typeof loadTime
=== 'number' ) {
1193 $( '<div>' ).append(
1194 new OO
.ui
.LabelWidget( {
1195 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1201 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1202 // Flush all saved tokens in case one of them is the bad one.
1203 Util
.markTokensBad();
1204 button
= new OO
.ui
.ButtonWidget( {
1205 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1207 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1208 .on( 'click', button
.setDisabled
, [ true ], button
)
1209 .$element
.appendTo( $result
);
1211 }, function ( code
, data
) {
1212 var details
= 'HTTP error: ' + data
.exception
;
1215 new OO
.ui
.LabelWidget( {
1216 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1217 classes
: [ 'error' ]
1225 * Handler for the "Correct token and resubmit" button
1227 * Used on a 'badtoken' error, it re-fetches token parameters for all
1228 * pages and then re-submits the query.
1230 fixTokenAndResend: function () {
1231 var page
, subpages
, i
, k
,
1233 tokenWait
= { dummy
: true },
1234 checkPages
= [ pages
.main
],
1235 success = function ( k
) {
1236 delete tokenWait
[ k
];
1237 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1238 ApiSandbox
.sendRequest();
1241 failure = function ( k
) {
1242 delete tokenWait
[ k
];
1246 while ( checkPages
.length
) {
1247 page
= checkPages
.shift();
1249 if ( page
.tokenWidget
) {
1250 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1251 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1253 .done( success
.bind( page
.tokenWidget
, k
) )
1254 .fail( failure
.bind( page
.tokenWidget
, k
) );
1257 subpages
= page
.getSubpages();
1258 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1259 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1260 checkPages
.push( pages
[ subpages
[ i
].key
] );
1265 success( 'dummy', '' );
1269 * Reset validity indicators for all widgets
1271 updateValidityIndicators: function () {
1272 var page
, subpages
, i
,
1273 checkPages
= [ pages
.main
];
1275 while ( checkPages
.length
) {
1276 page
= checkPages
.shift();
1277 page
.apiCheckValid();
1278 subpages
= page
.getSubpages();
1279 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1280 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1281 checkPages
.push( pages
[ subpages
[ i
].key
] );
1289 * PageLayout for API modules
1293 * @extends OO.ui.PageLayout
1295 * @param {Object} [config] Configuration options
1297 ApiSandbox
.PageLayout = function ( config
) {
1298 config
= $.extend( { prefix
: '' }, config
);
1299 this.displayText
= config
.key
;
1300 this.apiModule
= config
.path
;
1301 this.prefix
= config
.prefix
;
1302 this.paramInfo
= null;
1303 this.apiIsValid
= true;
1304 this.loadFromQueryParams
= null;
1306 this.tokenWidget
= null;
1307 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1308 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1309 this.loadParamInfo();
1311 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1312 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1313 this.outlineItem
.setLevel( this.indentLevel
);
1314 this.outlineItem
.setLabel( this.displayText
);
1315 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1316 this.outlineItem
.setIconTitle(
1317 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1322 * Fetch module information for this page's module, then create UI
1324 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1325 var dynamicFieldset
, dynamicParamNameWidget
,
1327 removeDynamicParamWidget = function ( name
, layout
) {
1328 dynamicFieldset
.removeItems( [ layout
] );
1329 delete that
.widgets
[ name
];
1331 addDynamicParamWidget = function () {
1332 var name
, layout
, widget
, button
;
1334 // Check name is filled in
1335 name
= dynamicParamNameWidget
.getValue().trim();
1336 if ( name
=== '' ) {
1337 dynamicParamNameWidget
.focus();
1341 if ( that
.widgets
[ name
] !== undefined ) {
1342 windowManager
.openWindow( 'errorAlert', {
1343 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1347 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1355 widget
= Util
.createWidgetForParameter( {
1362 button
= new OO
.ui
.ButtonWidget( {
1364 flags
: 'destructive'
1366 layout
= new OO
.ui
.ActionFieldLayout(
1374 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1375 that
.widgets
[ name
] = widget
;
1376 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1379 dynamicParamNameWidget
.setValue( '' );
1382 this.$element
.empty()
1383 .append( new OO
.ui
.ProgressBarWidget( {
1385 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1388 Util
.fetchModuleInfo( this.apiModule
)
1389 .done( function ( pi
) {
1390 var prefix
, i
, j
, descriptionContainer
, widget
, layoutConfig
, button
, widgetField
, helpField
, tmp
, flag
, count
,
1392 deprecatedItems
= [],
1394 filterFmModules = function ( v
) {
1395 return v
.substr( -2 ) !== 'fm' ||
1396 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1398 widgetLabelOnClick = function () {
1399 var f
= this.getField();
1400 if ( $.isFunction( f
.setDisabled
) ) {
1401 f
.setDisabled( false );
1403 if ( $.isFunction( f
.focus
) ) {
1408 // This is something of a hack. We always want the 'format' and
1409 // 'action' parameters from the main module to be specified,
1410 // and for 'format' we also want to simplify the dropdown since
1411 // we always send the 'fm' variant.
1412 if ( that
.apiModule
=== 'main' ) {
1413 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1414 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1415 pi
.parameters
[ i
].required
= true;
1416 delete pi
.parameters
[ i
][ 'default' ];
1418 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1419 tmp
= pi
.parameters
[ i
].type
;
1420 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1421 availableFormats
[ tmp
[ j
] ] = true;
1423 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1424 pi
.parameters
[ i
][ 'default' ] = 'json';
1425 pi
.parameters
[ i
].required
= true;
1430 // Hide the 'wrappedhtml' parameter on format modules
1431 if ( pi
.group
=== 'format' ) {
1432 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1433 return p
.name
!== 'wrappedhtml';
1437 that
.paramInfo
= pi
;
1439 items
.push( new OO
.ui
.FieldLayout(
1440 new OO
.ui
.Widget( {} ).toggle( false ), {
1442 label
: Util
.parseHTML( pi
.description
)
1446 if ( pi
.helpurls
.length
) {
1447 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1449 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1454 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1455 return $( '<li>' ).append( $( '<a>' )
1456 .attr( { href
: link
, target
: '_blank' } )
1464 if ( pi
.examples
.length
) {
1465 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1467 label
: mw
.message( 'apisandbox-examples' ).text(),
1472 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1474 .attr( 'href', '#' + example
.query
)
1475 .html( example
.description
);
1476 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1477 return $( '<li>' ).append( a
);
1483 if ( buttons
.length
) {
1484 items
.push( new OO
.ui
.FieldLayout(
1485 new OO
.ui
.ButtonGroupWidget( {
1487 } ), { align
: 'top' }
1491 if ( pi
.parameters
.length
) {
1492 prefix
= that
.prefix
+ pi
.prefix
;
1493 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1494 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1495 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1496 if ( pi
.parameters
[ i
].tokentype
) {
1497 that
.tokenWidget
= widget
;
1500 descriptionContainer
= $( '<div>' );
1502 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1503 tmp
.filter( 'dl' ).makeCollapsible( {
1505 } ).children( '.mw-collapsible-toggle' ).each( function () {
1506 var $this = $( this );
1507 $this.parent().prev( 'p' ).append( $this );
1509 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1511 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1512 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1513 descriptionContainer
.append( $( '<div>' )
1515 .append( Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] ) )
1521 switch ( pi
.parameters
[ i
].type
) {
1524 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1528 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1529 descriptionContainer
.append( $( '<div>' )
1533 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1536 Util
.parseMsg( 'apisandbox-param-limit' )
1540 descriptionContainer
.append( $( '<div>' )
1543 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1545 Util
.parseMsg( 'apisandbox-param-limit' )
1553 if ( pi
.parameters
[ i
].min
!== undefined ) {
1556 if ( pi
.parameters
[ i
].max
!== undefined ) {
1560 descriptionContainer
.append( $( '<div>' )
1562 .append( Util
.parseMsg(
1563 'api-help-param-integer-' + tmp
,
1564 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1565 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1572 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1574 count
= pi
.parameters
[ i
].type
.length
;
1578 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1580 if ( flag
&& !( widget
instanceof OO
.ui
.CapsuleMultiselectWidget
) &&
1582 widget
instanceof OptionalWidget
&&
1583 widget
.widget
instanceof OO
.ui
.CapsuleMultiselectWidget
1586 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1588 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1590 mw
.message( 'api-help-param-multi-max',
1591 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1596 descriptionContainer
.append( $( '<div>' )
1598 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1602 if ( 'maxbytes' in pi
.parameters
[ i
] ) {
1603 descriptionContainer
.append( $( '<div>' )
1605 .append( Util
.parseMsg( 'api-help-param-maxbytes', pi
.parameters
[ i
].maxbytes
) )
1608 if ( 'maxchars' in pi
.parameters
[ i
] ) {
1609 descriptionContainer
.append( $( '<div>' )
1611 .append( Util
.parseMsg( 'api-help-param-maxchars', pi
.parameters
[ i
].maxchars
) )
1614 helpField
= new OO
.ui
.FieldLayout(
1617 classes
: [ 'mw-apisandbox-spacer' ]
1620 classes
: [ 'mw-apisandbox-help-field' ],
1621 label
: descriptionContainer
1627 classes
: [ 'mw-apisandbox-widget-field' ],
1628 label
: prefix
+ pi
.parameters
[ i
].name
1631 if ( pi
.parameters
[ i
].tokentype
) {
1632 button
= new OO
.ui
.ButtonWidget( {
1633 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1635 button
.on( 'click', widget
.fetchToken
, [], widget
);
1637 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1639 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1642 // We need our own click handler on the widget label to
1643 // turn off the disablement.
1644 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1646 // Don't grey out the label when the field is disabled,
1647 // it makes it too hard to read and our "disabled"
1648 // isn't really disabled.
1649 widgetField
.onFieldDisable( false );
1650 widgetField
.onFieldDisable
= $.noop
;
1652 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1653 deprecatedItems
.push( widgetField
, helpField
);
1655 items
.push( widgetField
, helpField
);
1660 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1661 items
.push( new OO
.ui
.FieldLayout(
1662 new OO
.ui
.Widget( {} ).toggle( false ), {
1664 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1669 that
.$element
.empty();
1671 new OO
.ui
.FieldsetLayout( {
1672 label
: that
.displayText
1673 } ).addItems( items
)
1674 .$element
.appendTo( that
.$element
);
1676 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1677 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1678 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1679 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1680 } ).on( 'enter', addDynamicParamWidget
);
1681 dynamicFieldset
.addItems( [
1682 new OO
.ui
.FieldLayout(
1683 new OO
.ui
.Widget( {} ).toggle( false ), {
1685 label
: Util
.parseHTML( pi
.dynamicparameters
)
1688 new OO
.ui
.ActionFieldLayout(
1689 dynamicParamNameWidget
,
1690 new OO
.ui
.ButtonWidget( {
1692 flags
: 'progressive'
1693 } ).on( 'click', addDynamicParamWidget
),
1695 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1702 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1703 dynamicFieldset
.$element
1705 .appendTo( that
.$element
);
1708 if ( deprecatedItems
.length
) {
1709 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1712 $( '<legend>' ).append(
1713 new OO
.ui
.ToggleButtonWidget( {
1714 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1715 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1719 .appendTo( that
.$element
);
1722 // Load stored params, if any, then update the booklet if we
1723 // have subpages (or else just update our valid-indicator).
1724 tmp
= that
.loadFromQueryParams
;
1725 that
.loadFromQueryParams
= null;
1726 if ( $.isPlainObject( tmp
) ) {
1727 that
.loadQueryParams( tmp
);
1729 if ( that
.getSubpages().length
> 0 ) {
1730 ApiSandbox
.updateUI( tmp
);
1732 that
.apiCheckValid();
1734 } ).fail( function ( code
, detail
) {
1735 that
.$element
.empty()
1737 new OO
.ui
.LabelWidget( {
1738 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1739 classes
: [ 'error' ]
1741 new OO
.ui
.ButtonWidget( {
1742 label
: mw
.message( 'apisandbox-retry' ).text()
1743 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1749 * Check that all widgets on the page are in a valid state.
1753 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1756 if ( this.paramInfo
=== null ) {
1757 return $.Deferred().resolve( false ).promise();
1759 return $.when
.apply( $, $.map( this.widgets
, function ( widget
) {
1760 return widget
.apiCheckValid();
1761 } ) ).then( function () {
1762 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1763 if ( that
.getOutlineItem() ) {
1764 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1765 that
.getOutlineItem().setIconTitle(
1766 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1769 return $.Deferred().resolve( that
.apiIsValid
).promise();
1775 * Load form fields from query parameters
1777 * @param {Object} params
1779 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1780 if ( this.paramInfo
=== null ) {
1781 this.loadFromQueryParams
= params
;
1783 $.each( this.widgets
, function ( name
, widget
) {
1784 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1785 widget
.setApiValue( v
);
1791 * Load query params from form fields
1793 * @param {Object} params Write query parameters into this object
1794 * @param {Object} displayParams Write query parameters for display into this object
1796 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1797 $.each( this.widgets
, function ( name
, widget
) {
1798 var value
= widget
.getApiValue();
1799 if ( value
!== undefined ) {
1800 params
[ name
] = value
;
1801 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1802 value
= widget
.getApiValueForDisplay();
1804 displayParams
[ name
] = value
;
1810 * Fetch a list of subpage names loaded by this page
1814 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1816 $.each( this.widgets
, function ( name
, widget
) {
1818 if ( $.isFunction( widget
.getSubmodules
) ) {
1819 submodules
= widget
.getSubmodules();
1820 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1822 key
: name
+ '=' + submodules
[ i
].value
,
1823 path
: submodules
[ i
].path
,
1824 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1833 * A wrapper for a widget that provides an enable/disable button
1838 * @param {OO.ui.Widget} widget
1839 * @param {Object} [config] Configuration options
1841 function OptionalWidget( widget
, config
) {
1844 config
= config
|| {};
1846 this.widget
= widget
;
1847 this.$cover
= config
.$cover
||
1848 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-cover' );
1849 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
1850 .on( 'change', this.onCheckboxChange
, [], this );
1852 OptionalWidget
[ 'super' ].call( this, config
);
1854 // Forward most methods for convenience
1855 for ( k
in this.widget
) {
1856 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
1857 this[ k
] = this.widget
[ k
].bind( this.widget
);
1861 this.$cover
.on( 'click', this.onOverlayClick
.bind( this ) );
1864 .addClass( 'mw-apisandbox-optionalWidget' )
1867 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
1868 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
1871 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
1872 this.checkbox
.$element
1877 this.setDisabled( widget
.isDisabled() );
1879 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
1880 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
1881 this.setDisabled( !checked
);
1883 OptionalWidget
.prototype.onOverlayClick = function () {
1884 this.setDisabled( false );
1885 if ( $.isFunction( this.widget
.focus
) ) {
1886 this.widget
.focus();
1889 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
1890 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
1891 this.widget
.setDisabled( this.isDisabled() );
1892 this.checkbox
.setSelected( !this.isDisabled() );
1893 this.$cover
.toggle( this.isDisabled() );
1897 $( ApiSandbox
.init
);
1899 module
.exports
= ApiSandbox
;
1901 }( jQuery
, mediaWiki
, OO
) );