1 ( function ( $, mw
, OO
) {
3 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
4 $content
, panel
, booklet
, oldhash
, windowManager
,
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' ],
621 widget
.paramInfo
= pi
;
622 $.extend( widget
, WidgetMethods
.tagWidget
);
625 if ( !innerWidget
.isDisabled() ) {
626 innerWidget
.apiCheckValid().done( function ( ok
) {
628 widget
.addTag( innerWidget
.getApiValue() );
629 innerWidget
.setApiValue( undefined );
636 if ( multiModeInput
) {
637 multiModeInput
.on( 'enter', func
);
639 multiModeButton
.on( 'click', func
);
642 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
643 finalWidget
= widget
;
645 finalWidget
= new OptionalWidget( widget
);
646 finalWidget
.paramInfo
= pi
;
647 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
648 if ( widget
.getSubmodules
) {
649 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
650 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
652 finalWidget
.setDisabled( true );
655 widget
.setApiValue( pi
[ 'default' ] );
661 * Parse an HTML string and call Util.fixupHTML()
663 * @param {string} html HTML to parse
666 parseHTML: function ( html
) {
667 var $ret
= $( $.parseHTML( html
) );
668 return Util
.fixupHTML( $ret
);
672 * Parse an i18n message and call Util.fixupHTML()
674 * @param {string} key Key of message to get
675 * @param {...Mixed} parameters Values for $N replacements
678 parseMsg: function () {
679 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
680 return Util
.fixupHTML( $ret
);
684 * Fix HTML for ApiSandbox display
687 * - Add target="_blank" to any links
689 * @param {jQuery} $html DOM to process
692 fixupHTML: function ( $html
) {
693 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
694 .filter( '[href]:not([target])' )
695 .attr( 'target', '_blank' );
700 * Format a request and return a bunch of menu option widgets
702 * @param {Object} displayParams Query parameters, sanitized for display.
703 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
704 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
706 formatRequest: function ( displayParams
, rawParams
) {
709 new OO
.ui
.MenuOptionWidget( {
710 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
711 data
: new OO
.ui
.FieldLayout(
712 new OO
.ui
.TextInputWidget( {
714 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
716 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
720 new OO
.ui
.MenuOptionWidget( {
721 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
722 data
: new OO
.ui
.FieldLayout(
723 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
724 classes
: [ 'mw-apisandbox-textInputCode' ],
728 value
: JSON
.stringify( displayParams
, null, '\t' )
730 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
732 ).on( 'toggle', function ( visible
) {
734 // Call updatePosition instead of adjustSize
735 // because the latter has weird caching
736 // behavior and the former bypasses it.
737 jsonInput
.updatePosition();
743 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
749 * Event handler for when formatDropdown's selection changes
751 onFormatDropdownChange: function () {
753 menu
= formatDropdown
.getMenu(),
754 items
= menu
.getItems(),
755 selectedField
= menu
.findSelectedItem() ? menu
.findSelectedItem().getData() : null;
757 for ( i
= 0; i
< items
.length
; i
++ ) {
758 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
764 * Interface to ApiSandbox UI
766 * @class mw.special.ApiSandbox
772 * Automatically called on $.ready()
777 $content
= $( '#mw-apisandbox' );
779 windowManager
= new OO
.ui
.WindowManager();
780 $( 'body' ).append( windowManager
.$element
);
781 windowManager
.addWindows( {
782 errorAlert
: new OO
.ui
.MessageDialog()
785 $toolbar
= $( '<div>' )
786 .addClass( 'mw-apisandbox-toolbar' )
788 new OO
.ui
.ButtonWidget( {
789 label
: mw
.message( 'apisandbox-submit' ).text(),
790 flags
: [ 'primary', 'progressive' ]
791 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
792 new OO
.ui
.ButtonWidget( {
793 label
: mw
.message( 'apisandbox-reset' ).text(),
795 } ).on( 'click', ApiSandbox
.resetUI
).$element
798 booklet
= new OO
.ui
.BookletLayout( {
804 panel
= new OO
.ui
.PanelLayout( {
805 classes
: [ 'mw-apisandbox-container' ],
806 content
: [ booklet
],
811 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
813 // Parse the current hash string
814 if ( !ApiSandbox
.loadFromHash() ) {
815 ApiSandbox
.updateUI();
818 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
822 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
824 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
826 .append( panel
.$element
)
831 * Update the current query when the page hash changes
833 * @return {boolean} Successful
835 loadFromHash: function () {
837 hash
= location
.hash
;
839 if ( oldhash
=== hash
) {
847 // I'm surprised this doesn't seem to exist in jQuery or mw.util.
849 hash
= hash
.replace( /\+/g, '%20' );
850 re
= /([^&=#]+)=?([^&#]*)/g;
851 while ( ( m
= re
.exec( hash
) ) ) {
852 params
[ decodeURIComponent( m
[ 1 ] ) ] = decodeURIComponent( m
[ 2 ] );
855 ApiSandbox
.updateUI( params
);
860 * Update the pages in the booklet
862 * @param {Object} [params] Optional query parameters to load
864 updateUI: function ( params
) {
865 var i
, page
, subpages
, j
, removePages
,
868 if ( !$.isPlainObject( params
) ) {
872 if ( updatingBooklet
) {
875 updatingBooklet
= true;
877 if ( params
!== undefined ) {
878 pages
.main
.loadQueryParams( params
);
880 addPages
.push( pages
.main
);
881 if ( resultPage
!== null ) {
882 addPages
.push( resultPage
);
884 pages
.main
.apiCheckValid();
887 while ( addPages
.length
) {
888 page
= addPages
.shift();
889 if ( bookletPages
[ i
] !== page
) {
890 for ( j
= i
; j
< bookletPages
.length
; j
++ ) {
891 if ( bookletPages
[ j
].getName() === page
.getName() ) {
892 bookletPages
.splice( j
, 1 );
895 bookletPages
.splice( i
, 0, page
);
896 booklet
.addPages( [ page
], i
);
900 if ( page
.getSubpages
) {
901 subpages
= page
.getSubpages();
902 for ( j
= 0; j
< subpages
.length
; j
++ ) {
903 if ( !pages
.hasOwnProperty( subpages
[ j
].key
) ) {
904 subpages
[ j
].indentLevel
= page
.indentLevel
+ 1;
905 pages
[ subpages
[ j
].key
] = new ApiSandbox
.PageLayout( subpages
[ j
] );
907 if ( params
!== undefined ) {
908 pages
[ subpages
[ j
].key
].loadQueryParams( params
);
910 addPages
.splice( j
, 0, pages
[ subpages
[ j
].key
] );
911 pages
[ subpages
[ j
].key
].apiCheckValid();
916 if ( bookletPages
.length
> i
) {
917 removePages
= bookletPages
.splice( i
, bookletPages
.length
- i
);
918 booklet
.removePages( removePages
);
921 if ( !booklet
.getCurrentPageName() ) {
922 booklet
.selectFirstSelectablePage();
925 updatingBooklet
= false;
930 * Reset button handler
932 resetUI: function () {
933 suppressErrors
= true;
935 main
: new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } )
938 ApiSandbox
.updateUI();
942 * Submit button handler
944 * @param {Object} [params] Use this set of params instead of those in the form fields.
945 * The form fields will be updated to match.
947 sendRequest: function ( params
) {
948 var page
, subpages
, i
, query
, $result
, $focus
,
949 progress
, $progressText
, progressLoading
,
951 paramsAreForced
= !!params
,
954 checkPages
= [ pages
.main
];
956 // Blur any focused widget before submit, because
957 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
958 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
959 if ( $focus
.length
) {
963 suppressErrors
= false;
965 // save widget state in params (or load from it if we are forced)
966 if ( paramsAreForced
) {
967 ApiSandbox
.updateUI( params
);
970 while ( checkPages
.length
) {
971 page
= checkPages
.shift();
972 if ( page
.tokenWidget
) {
973 tokenWidgets
.push( page
.tokenWidget
);
975 deferreds
= deferreds
.concat( page
.apiCheckValid() );
976 page
.getQueryParams( params
, displayParams
);
977 subpages
= page
.getSubpages();
978 for ( i
= 0; i
< subpages
.length
; i
++ ) {
979 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
980 checkPages
.push( pages
[ subpages
[ i
].key
] );
985 if ( !paramsAreForced
) {
986 // forced params means we are continuing a query; the base query should be preserved
987 baseRequestParams
= $.extend( {}, params
);
990 $.when
.apply( $, deferreds
).done( function () {
991 var formatItems
, menu
, selectedLabel
, deferred
, actions
, errorCount
;
993 // Count how many times `value` occurs in `array`.
994 function countValues( value
, array
) {
997 for ( i
= 0; i
< array
.length
; i
++ ) {
998 if ( array
[ i
] === value
) {
1005 errorCount
= countValues( false, arguments
);
1006 if ( errorCount
> 0 ) {
1010 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1014 if ( tokenWidgets
.length
) {
1015 // Check all token widgets' validity separately
1016 deferred
= $.when
.apply( $, tokenWidgets
.map( function ( w
) {
1017 return w
.apiCheckValid();
1020 deferred
.done( function () {
1021 // If only the tokens are invalid, offer to fix them
1022 var tokenErrorCount
= countValues( false, arguments
);
1023 if ( tokenErrorCount
=== errorCount
) {
1024 delete actions
[ 0 ].flags
;
1027 label
: mw
.message( 'apisandbox-results-fixtoken' ).text(),
1033 deferred
= $.Deferred().resolve();
1035 deferred
.always( function () {
1036 windowManager
.openWindow( 'errorAlert', {
1037 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1038 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1040 } ).closed
.then( function ( data
) {
1041 if ( data
&& data
.action
=== 'fix' ) {
1042 ApiSandbox
.fixTokenAndResend();
1049 query
= $.param( displayParams
);
1051 formatItems
= Util
.formatRequest( displayParams
, params
);
1053 // Force a 'fm' format with wrappedhtml=1, if available
1054 if ( params
.format
!== undefined ) {
1055 if ( availableFormats
.hasOwnProperty( params
.format
+ 'fm' ) ) {
1056 params
.format
= params
.format
+ 'fm';
1058 if ( params
.format
.substr( -2 ) === 'fm' ) {
1059 params
.wrappedhtml
= 1;
1063 progressLoading
= false;
1064 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1065 progress
= new OO
.ui
.ProgressBarWidget( {
1067 $content
: $progressText
1070 $result
= $( '<div>' )
1071 .append( progress
.$element
);
1073 resultPage
= page
= new OO
.ui
.PageLayout( '|results|', { expanded
: false } );
1074 page
.setupOutlineItem = function () {
1075 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1078 if ( !formatDropdown
) {
1079 formatDropdown
= new OO
.ui
.DropdownWidget( {
1080 menu
: { items
: [] },
1083 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1086 menu
= formatDropdown
.getMenu();
1087 selectedLabel
= menu
.findSelectedItem() ? menu
.findSelectedItem().getLabel() : '';
1088 if ( typeof selectedLabel
!== 'string' ) {
1089 selectedLabel
= selectedLabel
.text();
1091 menu
.clearItems().addItems( formatItems
);
1092 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1094 // Fire the event to update field visibilities
1095 Util
.onFormatDropdownChange();
1097 page
.$element
.empty()
1099 new OO
.ui
.FieldLayout(
1101 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1104 formatItems
.map( function ( item
) {
1105 return item
.getData().$element
;
1109 ApiSandbox
.updateUI();
1110 booklet
.setPage( '|results|' );
1112 location
.href
= oldhash
= '#' + query
;
1115 contentType
: 'multipart/form-data',
1118 var xhr
= new window
.XMLHttpRequest();
1119 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1120 if ( !progressLoading
) {
1121 if ( e
.lengthComputable
) {
1122 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1124 progress
.setProgress( false );
1128 xhr
.addEventListener( 'progress', function ( e
) {
1129 if ( !progressLoading
) {
1130 progressLoading
= true;
1131 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1133 if ( e
.lengthComputable
) {
1134 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1136 progress
.setProgress( false );
1142 .catch( function ( code
, data
, result
, jqXHR
) {
1143 var deferred
= $.Deferred();
1145 if ( code
!== 'http' ) {
1146 // Not really an error, work around mw.Api thinking it is.
1147 deferred
.resolve( result
, jqXHR
);
1150 deferred
.reject
.apply( deferred
, arguments
);
1152 return deferred
.promise();
1154 .then( function ( data
, jqXHR
) {
1155 var m
, loadTime
, button
, clear
,
1156 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1157 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1160 if ( loginSuppressed
!== 'false' ) {
1162 .addClass( 'warning' )
1163 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1164 .appendTo( $result
);
1166 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1167 data
= JSON
.parse( data
);
1168 if ( data
.modules
.length
) {
1169 mw
.loader
.load( data
.modules
);
1171 if ( data
.status
&& data
.status
!== 200 ) {
1173 .addClass( 'api-pretty-header api-pretty-status' )
1174 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1175 .appendTo( $result
);
1177 $result
.append( Util
.parseHTML( data
.html
) );
1178 loadTime
= data
.time
;
1179 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1180 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1181 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1182 loadTime
= parseInt( m
[ 1 ], 10 );
1186 .addClass( 'api-pretty-content' )
1188 .appendTo( $result
);
1190 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1192 $( '<div>' ).append(
1193 new OO
.ui
.ButtonWidget( {
1194 label
: mw
.message( 'apisandbox-continue' ).text()
1195 } ).on( 'click', function () {
1196 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1197 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1198 ( clear
= new OO
.ui
.ButtonWidget( {
1199 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1200 } ).on( 'click', function () {
1201 ApiSandbox
.updateUI( baseRequestParams
);
1202 clear
.setDisabled( true );
1203 booklet
.setPage( '|results|' );
1204 } ).setDisabled( !paramsAreForced
) ).$element
,
1205 new OO
.ui
.PopupButtonWidget( {
1210 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1218 if ( typeof loadTime
=== 'number' ) {
1220 $( '<div>' ).append(
1221 new OO
.ui
.LabelWidget( {
1222 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1228 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1229 // Flush all saved tokens in case one of them is the bad one.
1230 Util
.markTokensBad();
1231 button
= new OO
.ui
.ButtonWidget( {
1232 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1234 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1235 .on( 'click', button
.setDisabled
, [ true ], button
)
1236 .$element
.appendTo( $result
);
1238 }, function ( code
, data
) {
1239 var details
= 'HTTP error: ' + data
.exception
;
1242 new OO
.ui
.LabelWidget( {
1243 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1244 classes
: [ 'error' ]
1252 * Handler for the "Correct token and resubmit" button
1254 * Used on a 'badtoken' error, it re-fetches token parameters for all
1255 * pages and then re-submits the query.
1257 fixTokenAndResend: function () {
1258 var page
, subpages
, i
, k
,
1260 tokenWait
= { dummy
: true },
1261 checkPages
= [ pages
.main
],
1262 success = function ( k
) {
1263 delete tokenWait
[ k
];
1264 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1265 ApiSandbox
.sendRequest();
1268 failure = function ( k
) {
1269 delete tokenWait
[ k
];
1273 while ( checkPages
.length
) {
1274 page
= checkPages
.shift();
1276 if ( page
.tokenWidget
) {
1277 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1278 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1280 .done( success
.bind( page
.tokenWidget
, k
) )
1281 .fail( failure
.bind( page
.tokenWidget
, k
) );
1284 subpages
= page
.getSubpages();
1285 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1286 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1287 checkPages
.push( pages
[ subpages
[ i
].key
] );
1292 success( 'dummy', '' );
1296 * Reset validity indicators for all widgets
1298 updateValidityIndicators: function () {
1299 var page
, subpages
, i
,
1300 checkPages
= [ pages
.main
];
1302 while ( checkPages
.length
) {
1303 page
= checkPages
.shift();
1304 page
.apiCheckValid();
1305 subpages
= page
.getSubpages();
1306 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1307 if ( pages
.hasOwnProperty( subpages
[ i
].key
) ) {
1308 checkPages
.push( pages
[ subpages
[ i
].key
] );
1316 * PageLayout for API modules
1320 * @extends OO.ui.PageLayout
1322 * @param {Object} [config] Configuration options
1324 ApiSandbox
.PageLayout = function ( config
) {
1325 config
= $.extend( { prefix
: '', expanded
: false }, config
);
1326 this.displayText
= config
.key
;
1327 this.apiModule
= config
.path
;
1328 this.prefix
= config
.prefix
;
1329 this.paramInfo
= null;
1330 this.apiIsValid
= true;
1331 this.loadFromQueryParams
= null;
1333 this.tokenWidget
= null;
1334 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1335 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1336 this.loadParamInfo();
1338 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1339 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1340 this.outlineItem
.setLevel( this.indentLevel
);
1341 this.outlineItem
.setLabel( this.displayText
);
1342 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1343 this.outlineItem
.setIconTitle(
1344 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1349 * Fetch module information for this page's module, then create UI
1351 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1352 var dynamicFieldset
, dynamicParamNameWidget
,
1354 removeDynamicParamWidget = function ( name
, layout
) {
1355 dynamicFieldset
.removeItems( [ layout
] );
1356 delete that
.widgets
[ name
];
1358 addDynamicParamWidget = function () {
1359 var name
, layout
, widget
, button
;
1361 // Check name is filled in
1362 name
= dynamicParamNameWidget
.getValue().trim();
1363 if ( name
=== '' ) {
1364 dynamicParamNameWidget
.focus();
1368 if ( that
.widgets
[ name
] !== undefined ) {
1369 windowManager
.openWindow( 'errorAlert', {
1370 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1374 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1382 widget
= Util
.createWidgetForParameter( {
1389 button
= new OO
.ui
.ButtonWidget( {
1391 flags
: 'destructive'
1393 layout
= new OO
.ui
.ActionFieldLayout(
1401 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1402 that
.widgets
[ name
] = widget
;
1403 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1406 dynamicParamNameWidget
.setValue( '' );
1409 this.$element
.empty()
1410 .append( new OO
.ui
.ProgressBarWidget( {
1412 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1415 Util
.fetchModuleInfo( this.apiModule
)
1416 .done( function ( pi
) {
1417 var prefix
, i
, j
, descriptionContainer
, widget
, layoutConfig
, button
, widgetField
, helpField
, tmp
, flag
, count
,
1419 deprecatedItems
= [],
1421 filterFmModules = function ( v
) {
1422 return v
.substr( -2 ) !== 'fm' ||
1423 !availableFormats
.hasOwnProperty( v
.substr( 0, v
.length
- 2 ) );
1425 widgetLabelOnClick = function () {
1426 var f
= this.getField();
1427 if ( $.isFunction( f
.setDisabled
) ) {
1428 f
.setDisabled( false );
1430 if ( $.isFunction( f
.focus
) ) {
1435 // This is something of a hack. We always want the 'format' and
1436 // 'action' parameters from the main module to be specified,
1437 // and for 'format' we also want to simplify the dropdown since
1438 // we always send the 'fm' variant.
1439 if ( that
.apiModule
=== 'main' ) {
1440 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1441 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1442 pi
.parameters
[ i
].required
= true;
1443 delete pi
.parameters
[ i
][ 'default' ];
1445 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1446 tmp
= pi
.parameters
[ i
].type
;
1447 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1448 availableFormats
[ tmp
[ j
] ] = true;
1450 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1451 pi
.parameters
[ i
][ 'default' ] = 'json';
1452 pi
.parameters
[ i
].required
= true;
1457 // Hide the 'wrappedhtml' parameter on format modules
1458 if ( pi
.group
=== 'format' ) {
1459 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1460 return p
.name
!== 'wrappedhtml';
1464 that
.paramInfo
= pi
;
1466 items
.push( new OO
.ui
.FieldLayout(
1467 new OO
.ui
.Widget( {} ).toggle( false ), {
1469 label
: Util
.parseHTML( pi
.description
)
1473 if ( pi
.helpurls
.length
) {
1474 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1476 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1481 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1482 return $( '<li>' ).append( $( '<a>' )
1483 .attr( { href
: link
, target
: '_blank' } )
1491 if ( pi
.examples
.length
) {
1492 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1494 label
: mw
.message( 'apisandbox-examples' ).text(),
1499 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1501 .attr( 'href', '#' + example
.query
)
1502 .html( example
.description
);
1503 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1504 return $( '<li>' ).append( a
);
1510 if ( buttons
.length
) {
1511 items
.push( new OO
.ui
.FieldLayout(
1512 new OO
.ui
.ButtonGroupWidget( {
1514 } ), { align
: 'top' }
1518 if ( pi
.parameters
.length
) {
1519 prefix
= that
.prefix
+ pi
.prefix
;
1520 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1521 widget
= Util
.createWidgetForParameter( pi
.parameters
[ i
] );
1522 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = widget
;
1523 if ( pi
.parameters
[ i
].tokentype
) {
1524 that
.tokenWidget
= widget
;
1527 descriptionContainer
= $( '<div>' );
1529 tmp
= Util
.parseHTML( pi
.parameters
[ i
].description
);
1530 tmp
.filter( 'dl' ).makeCollapsible( {
1532 } ).children( '.mw-collapsible-toggle' ).each( function () {
1533 var $this = $( this );
1534 $this.parent().prev( 'p' ).append( $this );
1536 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1538 if ( pi
.parameters
[ i
].info
&& pi
.parameters
[ i
].info
.length
) {
1539 for ( j
= 0; j
< pi
.parameters
[ i
].info
.length
; j
++ ) {
1540 descriptionContainer
.append( $( '<div>' )
1542 .append( Util
.parseHTML( pi
.parameters
[ i
].info
[ j
] ) )
1548 switch ( pi
.parameters
[ i
].type
) {
1551 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1555 if ( pi
.parameters
[ i
].highmax
!== undefined ) {
1556 descriptionContainer
.append( $( '<div>' )
1560 'api-help-param-limit2', pi
.parameters
[ i
].max
, pi
.parameters
[ i
].highmax
1563 Util
.parseMsg( 'apisandbox-param-limit' )
1567 descriptionContainer
.append( $( '<div>' )
1570 Util
.parseMsg( 'api-help-param-limit', pi
.parameters
[ i
].max
),
1572 Util
.parseMsg( 'apisandbox-param-limit' )
1580 if ( pi
.parameters
[ i
].min
!== undefined ) {
1583 if ( pi
.parameters
[ i
].max
!== undefined ) {
1587 descriptionContainer
.append( $( '<div>' )
1589 .append( Util
.parseMsg(
1590 'api-help-param-integer-' + tmp
,
1591 Util
.apiBool( pi
.parameters
[ i
].multi
) ? 2 : 1,
1592 pi
.parameters
[ i
].min
, pi
.parameters
[ i
].max
1599 if ( Array
.isArray( pi
.parameters
[ i
].type
) ) {
1601 count
= pi
.parameters
[ i
].type
.length
;
1605 if ( Util
.apiBool( pi
.parameters
[ i
].multi
) ) {
1607 if ( flag
&& !( widget
instanceof OO
.ui
.TagMultiselectWidget
) &&
1609 widget
instanceof OptionalWidget
&&
1610 widget
.widget
instanceof OO
.ui
.TagMultiselectWidget
1613 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1615 if ( count
> pi
.parameters
[ i
].lowlimit
) {
1617 mw
.message( 'api-help-param-multi-max',
1618 pi
.parameters
[ i
].lowlimit
, pi
.parameters
[ i
].highlimit
1623 descriptionContainer
.append( $( '<div>' )
1625 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1629 if ( 'maxbytes' in pi
.parameters
[ i
] ) {
1630 descriptionContainer
.append( $( '<div>' )
1632 .append( Util
.parseMsg( 'api-help-param-maxbytes', pi
.parameters
[ i
].maxbytes
) )
1635 if ( 'maxchars' in pi
.parameters
[ i
] ) {
1636 descriptionContainer
.append( $( '<div>' )
1638 .append( Util
.parseMsg( 'api-help-param-maxchars', pi
.parameters
[ i
].maxchars
) )
1641 helpField
= new OO
.ui
.FieldLayout(
1644 classes
: [ 'mw-apisandbox-spacer' ]
1647 classes
: [ 'mw-apisandbox-help-field' ],
1648 label
: descriptionContainer
1654 classes
: [ 'mw-apisandbox-widget-field' ],
1655 label
: prefix
+ pi
.parameters
[ i
].name
1658 if ( pi
.parameters
[ i
].tokentype
) {
1659 button
= new OO
.ui
.ButtonWidget( {
1660 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1662 button
.on( 'click', widget
.fetchToken
, [], widget
);
1664 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1666 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1669 // We need our own click handler on the widget label to
1670 // turn off the disablement.
1671 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1673 // Don't grey out the label when the field is disabled,
1674 // it makes it too hard to read and our "disabled"
1675 // isn't really disabled.
1676 widgetField
.onFieldDisable( false );
1677 widgetField
.onFieldDisable
= $.noop
;
1679 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1680 deprecatedItems
.push( widgetField
, helpField
);
1682 items
.push( widgetField
, helpField
);
1687 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1688 items
.push( new OO
.ui
.FieldLayout(
1689 new OO
.ui
.Widget( {} ).toggle( false ), {
1691 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1696 that
.$element
.empty();
1698 new OO
.ui
.FieldsetLayout( {
1699 label
: that
.displayText
1700 } ).addItems( items
)
1701 .$element
.appendTo( that
.$element
);
1703 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1704 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1705 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1706 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1707 } ).on( 'enter', addDynamicParamWidget
);
1708 dynamicFieldset
.addItems( [
1709 new OO
.ui
.FieldLayout(
1710 new OO
.ui
.Widget( {} ).toggle( false ), {
1712 label
: Util
.parseHTML( pi
.dynamicparameters
)
1715 new OO
.ui
.ActionFieldLayout(
1716 dynamicParamNameWidget
,
1717 new OO
.ui
.ButtonWidget( {
1719 flags
: 'progressive'
1720 } ).on( 'click', addDynamicParamWidget
),
1722 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1729 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1730 dynamicFieldset
.$element
1732 .appendTo( that
.$element
);
1735 if ( deprecatedItems
.length
) {
1736 tmp
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1739 $( '<legend>' ).append(
1740 new OO
.ui
.ToggleButtonWidget( {
1741 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1742 } ).on( 'change', tmp
.toggle
, [], tmp
).$element
1746 .appendTo( that
.$element
);
1749 // Load stored params, if any, then update the booklet if we
1750 // have subpages (or else just update our valid-indicator).
1751 tmp
= that
.loadFromQueryParams
;
1752 that
.loadFromQueryParams
= null;
1753 if ( $.isPlainObject( tmp
) ) {
1754 that
.loadQueryParams( tmp
);
1756 if ( that
.getSubpages().length
> 0 ) {
1757 ApiSandbox
.updateUI( tmp
);
1759 that
.apiCheckValid();
1761 } ).fail( function ( code
, detail
) {
1762 that
.$element
.empty()
1764 new OO
.ui
.LabelWidget( {
1765 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1766 classes
: [ 'error' ]
1768 new OO
.ui
.ButtonWidget( {
1769 label
: mw
.message( 'apisandbox-retry' ).text()
1770 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1776 * Check that all widgets on the page are in a valid state.
1778 * @return {jQuery.Promise[]} One promise for each widget, resolved with `false` if invalid
1780 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1781 var promises
, that
= this;
1783 if ( this.paramInfo
=== null ) {
1786 promises
= $.map( this.widgets
, function ( widget
) {
1787 return widget
.apiCheckValid();
1789 $.when
.apply( $, promises
).then( function () {
1790 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
1791 if ( that
.getOutlineItem() ) {
1792 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
1793 that
.getOutlineItem().setIconTitle(
1794 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1803 * Load form fields from query parameters
1805 * @param {Object} params
1807 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
1808 if ( this.paramInfo
=== null ) {
1809 this.loadFromQueryParams
= params
;
1811 $.each( this.widgets
, function ( name
, widget
) {
1812 var v
= params
.hasOwnProperty( name
) ? params
[ name
] : undefined;
1813 widget
.setApiValue( v
);
1819 * Load query params from form fields
1821 * @param {Object} params Write query parameters into this object
1822 * @param {Object} displayParams Write query parameters for display into this object
1824 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
1825 $.each( this.widgets
, function ( name
, widget
) {
1826 var value
= widget
.getApiValue();
1827 if ( value
!== undefined ) {
1828 params
[ name
] = value
;
1829 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
1830 value
= widget
.getApiValueForDisplay();
1832 displayParams
[ name
] = value
;
1838 * Fetch a list of subpage names loaded by this page
1842 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
1844 $.each( this.widgets
, function ( name
, widget
) {
1846 if ( $.isFunction( widget
.getSubmodules
) ) {
1847 submodules
= widget
.getSubmodules();
1848 for ( i
= 0; i
< submodules
.length
; i
++ ) {
1850 key
: name
+ '=' + submodules
[ i
].value
,
1851 path
: submodules
[ i
].path
,
1852 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
1860 $( ApiSandbox
.init
);
1862 module
.exports
= ApiSandbox
;
1864 }( jQuery
, mediaWiki
, OO
) );