1 /* eslint-disable no-restricted-properties */
2 ( function ( $, mw
, OO
) {
4 var ApiSandbox
, Util
, WidgetMethods
, Validators
,
5 $content
, panel
, booklet
, oldhash
, windowManager
,
11 suppressErrors
= true,
12 updatingBooklet
= false,
18 * A wrapper for a widget that provides an enable/disable button
23 * @param {OO.ui.Widget} widget
24 * @param {Object} [config] Configuration options
26 function OptionalWidget( widget
, config
) {
29 config
= config
|| {};
32 this.$cover
= config
.$cover
||
33 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-cover' );
34 this.checkbox
= new OO
.ui
.CheckboxInputWidget( config
.checkbox
)
35 .on( 'change', this.onCheckboxChange
, [], this );
37 OptionalWidget
[ 'super' ].call( this, config
);
39 // Forward most methods for convenience
40 for ( k
in this.widget
) {
41 if ( $.isFunction( this.widget
[ k
] ) && !this[ k
] ) {
42 this[ k
] = this.widget
[ k
].bind( this.widget
);
46 widget
.connect( this, {
47 change
: [ this.emit
, 'change' ]
50 this.$cover
.on( 'click', this.onOverlayClick
.bind( this ) );
53 .addClass( 'mw-apisandbox-optionalWidget' )
56 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-fields' ).append(
57 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-widget' ).append(
60 $( '<div>' ).addClass( 'mw-apisandbox-optionalWidget-checkbox' ).append(
61 this.checkbox
.$element
66 this.setDisabled( widget
.isDisabled() );
68 OO
.inheritClass( OptionalWidget
, OO
.ui
.Widget
);
69 OptionalWidget
.prototype.onCheckboxChange = function ( checked
) {
70 this.setDisabled( !checked
);
72 OptionalWidget
.prototype.onOverlayClick = function () {
73 this.setDisabled( false );
74 if ( $.isFunction( this.widget
.focus
) ) {
78 OptionalWidget
.prototype.setDisabled = function ( disabled
) {
79 OptionalWidget
[ 'super' ].prototype.setDisabled
.call( this, disabled
);
80 this.widget
.setDisabled( this.isDisabled() );
81 this.checkbox
.setSelected( !this.isDisabled() );
82 this.$cover
.toggle( this.isDisabled() );
83 this.emit( 'change' );
89 getApiValue: function () {
90 return this.getValue();
92 setApiValue: function ( v
) {
93 if ( v
=== undefined ) {
94 v
= this.paramInfo
[ 'default' ];
98 apiCheckValid: function () {
100 return this.getValidity().then( function () {
101 return $.Deferred().resolve( true ).promise();
103 return $.Deferred().resolve( false ).promise();
104 } ).done( function ( ok
) {
105 ok
= ok
|| suppressErrors
;
106 that
.setIcon( ok
? null : 'alert' );
107 that
.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
112 dateTimeInputWidget
: {
113 getValidity: function () {
114 if ( !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '' ) {
115 return $.Deferred().resolve().promise();
117 return $.Deferred().reject().promise();
123 alertTokenError: function ( code
, error
) {
124 windowManager
.openWindow( 'errorAlert', {
125 title
: Util
.parseMsg( 'apisandbox-results-fixtoken-fail', this.paramInfo
.tokentype
),
130 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
136 fetchToken: function () {
138 return api
.getToken( this.paramInfo
.tokentype
)
139 .done( this.setApiValue
.bind( this ) )
140 .fail( this.alertTokenError
.bind( this ) )
141 .always( this.popPending
.bind( this ) );
143 setApiValue: function ( v
) {
144 WidgetMethods
.textInputWidget
.setApiValue
.call( this, v
);
145 if ( v
=== '123ABC' ) {
152 getApiValueForDisplay: function () {
157 toggleSwitchWidget
: {
158 getApiValue: function () {
159 return this.getValue() ? 1 : undefined;
161 setApiValue: function ( v
) {
162 this.setValue( Util
.apiBool( v
) );
164 apiCheckValid: function () {
165 return $.Deferred().resolve( true ).promise();
170 getApiValue: function () {
171 var item
= this.getMenu().findSelectedItem();
172 return item
=== null ? undefined : item
.getData();
174 setApiValue: function ( v
) {
175 var menu
= this.getMenu();
177 if ( v
=== undefined ) {
178 v
= this.paramInfo
[ 'default' ];
180 if ( v
=== undefined ) {
183 menu
.selectItemByData( String( v
) );
186 apiCheckValid: function () {
187 var ok
= this.getApiValue() !== undefined || suppressErrors
;
188 this.setIcon( ok
? null : 'alert' );
189 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
190 return $.Deferred().resolve( ok
).promise();
195 parseApiValue: function ( v
) {
196 if ( v
=== undefined || v
=== '' || v
=== '\x1f' ) {
200 if ( v
[ 0 ] !== '\x1f' ) {
201 return v
.split( '|' );
203 return v
.substr( 1 ).split( '\x1f' );
207 getApiValueForTemplates: function () {
208 return this.isDisabled() ? this.parseApiValue( this.paramInfo
[ 'default' ] ) : this.getValue();
210 getApiValue: function () {
211 var items
= this.getValue();
212 if ( items
.join( '' ).indexOf( '|' ) === -1 ) {
213 return items
.join( '|' );
215 return '\x1f' + items
.join( '\x1f' );
218 setApiValue: function ( v
) {
219 if ( v
=== undefined ) {
220 v
= this.paramInfo
[ 'default' ];
222 this.setValue( this.parseApiValue( v
) );
224 apiCheckValid: function () {
228 if ( !suppressErrors
) {
229 ok
= this.getApiValue() !== undefined && !(
230 pi
.allspecifier
!== undefined &&
231 this.getValue().length
> 1 &&
232 this.getValue().indexOf( pi
.allspecifier
) !== -1
236 this.setIcon( ok
? null : 'alert' );
237 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
238 return $.Deferred().resolve( ok
).promise();
240 createTagItemWidget: function ( data
, label
) {
241 var item
= OO
.ui
.TagMultiselectWidget
.prototype.createTagItemWidget
.call( this, data
, label
);
242 if ( this.paramInfo
.deprecatedvalues
&&
243 this.paramInfo
.deprecatedvalues
.indexOf( data
) >= 0
245 item
.$element
.addClass( 'apihelp-deprecated-value' );
252 getApiValue: function () {
253 return this.isDisabled() ? undefined : this.widget
.getApiValue();
255 setApiValue: function ( v
) {
256 this.setDisabled( v
=== undefined );
257 this.widget
.setApiValue( v
);
259 apiCheckValid: function () {
260 if ( this.isDisabled() ) {
261 return $.Deferred().resolve( true ).promise();
263 return this.widget
.apiCheckValid();
269 single: function () {
270 var v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
271 return v
=== undefined ? [] : [ { value
: v
, path
: this.paramInfo
.submodules
[ v
] } ];
274 var map
= this.paramInfo
.submodules
,
275 v
= this.isDisabled() ? this.paramInfo
[ 'default' ] : this.getApiValue();
276 return v
=== undefined || v
=== '' ? [] : String( v
).split( '|' ).map( function ( v
) {
277 return { value
: v
, path
: map
[ v
] };
283 getApiValueForDisplay: function () {
286 getApiValue: function () {
287 return this.getValue();
289 setApiValue: function () {
292 apiCheckValid: function () {
293 var ok
= this.getValue() !== null || suppressErrors
;
294 this.setIcon( ok
? null : 'alert' );
295 this.setIconTitle( ok
? '' : mw
.message( 'apisandbox-alert-field' ).plain() );
296 return $.Deferred().resolve( ok
).promise();
302 generic: function () {
303 return !Util
.apiBool( this.paramInfo
.required
) || this.getApiValue() !== '';
308 * @class mw.special.ApiSandbox.Util
313 * Fetch API module info
315 * @param {string} module Module to fetch data for
316 * @return {jQuery.Promise}
318 fetchModuleInfo: function ( module
) {
320 deferred
= $.Deferred();
322 if ( Object
.prototype.hasOwnProperty
.call( moduleInfoCache
, module
) ) {
324 .resolve( moduleInfoCache
[ module
] )
325 .promise( { abort: function () {} } );
327 apiPromise
= api
.post( {
331 uselang
: mw
.config
.get( 'wgUserLanguage' )
332 } ).done( function ( data
) {
335 if ( data
.warnings
&& data
.warnings
.paraminfo
) {
336 deferred
.reject( '???', data
.warnings
.paraminfo
[ '*' ] );
340 info
= data
.paraminfo
.modules
;
341 if ( !info
|| info
.length
!== 1 || info
[ 0 ].path
!== module
) {
342 deferred
.reject( '???', 'No module data returned' );
346 moduleInfoCache
[ module
] = info
[ 0 ];
347 deferred
.resolve( info
[ 0 ] );
348 } ).fail( function ( code
, details
) {
349 if ( code
=== 'http' ) {
350 details
= 'HTTP error: ' + details
.exception
;
351 } else if ( details
.error
) {
352 details
= details
.error
.info
;
354 deferred
.reject( code
, details
);
357 .promise( { abort
: apiPromise
.abort
} );
362 * Mark all currently-in-use tokens as bad
364 markTokensBad: function () {
365 var page
, subpages
, i
,
366 checkPages
= [ pages
.main
];
368 while ( checkPages
.length
) {
369 page
= checkPages
.shift();
371 if ( page
.tokenWidget
) {
372 api
.badToken( page
.tokenWidget
.paramInfo
.tokentype
);
375 subpages
= page
.getSubpages();
376 for ( i
= 0; i
< subpages
.length
; i
++ ) {
377 if ( Object
.prototype.hasOwnProperty
.call( pages
, subpages
[ i
].key
) ) {
378 checkPages
.push( pages
[ subpages
[ i
].key
] );
385 * Test an API boolean
387 * @param {Mixed} value
390 apiBool: function ( value
) {
391 return value
!== undefined && value
!== false;
395 * Create a widget for a parameter.
397 * @param {Object} pi Parameter info from API
398 * @param {Object} opts Additional options
399 * @return {OO.ui.Widget}
401 createWidgetForParameter: function ( pi
, opts
) {
402 var widget
, innerWidget
, finalWidget
, items
, $content
, func
,
403 multiModeButton
= null,
404 multiModeInput
= null,
405 multiModeAllowed
= false;
411 widget
= new OO
.ui
.ToggleSwitchWidget();
412 widget
.paramInfo
= pi
;
413 $.extend( widget
, WidgetMethods
.toggleSwitchWidget
);
414 pi
.required
= true; // Avoid wrapping in the non-required widget
419 if ( Util
.apiBool( pi
.multi
) ) {
420 widget
= new OO
.ui
.TagMultiselectWidget( {
421 allowArbitrary
: true,
422 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
425 widget
.paramInfo
= pi
;
426 $.extend( widget
, WidgetMethods
.tagWidget
);
428 widget
= new OO
.ui
.TextInputWidget( {
429 required
: Util
.apiBool( pi
.required
)
432 if ( !Util
.apiBool( pi
.multi
) ) {
433 widget
.paramInfo
= pi
;
434 $.extend( widget
, WidgetMethods
.textInputWidget
);
435 widget
.setValidation( Validators
.generic
);
437 if ( pi
.tokentype
) {
438 widget
.paramInfo
= pi
;
439 $.extend( widget
, WidgetMethods
.textInputWidget
);
440 $.extend( widget
, WidgetMethods
.tokenWidget
);
445 widget
= new OO
.ui
.MultilineTextInputWidget( {
446 required
: Util
.apiBool( pi
.required
)
448 widget
.paramInfo
= pi
;
449 $.extend( widget
, WidgetMethods
.textInputWidget
);
450 widget
.setValidation( Validators
.generic
);
454 widget
= new OO
.ui
.TextInputWidget( {
456 required
: Util
.apiBool( pi
.required
)
458 widget
.paramInfo
= pi
;
459 $.extend( widget
, WidgetMethods
.textInputWidget
);
460 $.extend( widget
, WidgetMethods
.passwordWidget
);
461 widget
.setValidation( Validators
.generic
);
462 multiModeAllowed
= true;
463 multiModeInput
= widget
;
467 widget
= new OO
.ui
.NumberInputWidget( {
468 required
: Util
.apiBool( pi
.required
),
471 widget
.setIcon
= widget
.input
.setIcon
.bind( widget
.input
);
472 widget
.setIconTitle
= widget
.input
.setIconTitle
.bind( widget
.input
);
473 widget
.getValidity
= widget
.input
.getValidity
.bind( widget
.input
);
474 widget
.paramInfo
= pi
;
475 $.extend( widget
, WidgetMethods
.textInputWidget
);
476 if ( Util
.apiBool( pi
.enforcerange
) ) {
477 widget
.setRange( pi
.min
|| -Infinity
, pi
.max
|| Infinity
);
479 multiModeAllowed
= true;
480 multiModeInput
= widget
;
484 widget
= new OO
.ui
.TextInputWidget( {
485 required
: Util
.apiBool( pi
.required
)
487 widget
.setValidation( function ( value
) {
488 var n
, pi
= this.paramInfo
;
490 if ( value
=== 'max' ) {
494 return !isNaN( n
) && isFinite( n
) &&
495 Math
.floor( n
) === n
&&
496 n
>= pi
.min
&& n
<= pi
.apiSandboxMax
;
499 pi
.min
= pi
.min
|| 0;
500 pi
.apiSandboxMax
= mw
.config
.get( 'apihighlimits' ) ? pi
.highmax
: pi
.max
;
501 widget
.paramInfo
= pi
;
502 $.extend( widget
, WidgetMethods
.textInputWidget
);
503 multiModeAllowed
= true;
504 multiModeInput
= widget
;
508 widget
= new mw
.widgets
.datetime
.DateTimeInputWidget( {
510 format
: '${year|0}-${month|0}-${day|0}T${hour|0}:${minute|0}:${second|0}${zone|short}'
512 required
: Util
.apiBool( pi
.required
),
515 widget
.paramInfo
= pi
;
516 $.extend( widget
, WidgetMethods
.textInputWidget
);
517 $.extend( widget
, WidgetMethods
.dateTimeInputWidget
);
518 multiModeAllowed
= true;
522 widget
= new OO
.ui
.SelectFileWidget();
523 widget
.paramInfo
= pi
;
524 $.extend( widget
, WidgetMethods
.uploadWidget
);
528 items
= $.map( mw
.config
.get( 'wgFormattedNamespaces' ), function ( name
, ns
) {
530 name
= mw
.message( 'blanknamespace' ).text();
532 return new OO
.ui
.MenuOptionWidget( { data
: ns
, label
: name
} );
533 } ).sort( function ( a
, b
) {
534 return a
.data
- b
.data
;
536 if ( Util
.apiBool( pi
.multi
) ) {
537 if ( pi
.allspecifier
!== undefined ) {
538 items
.unshift( new OO
.ui
.MenuOptionWidget( {
539 data
: pi
.allspecifier
,
540 label
: mw
.message( 'apisandbox-multivalue-all-namespaces', pi
.allspecifier
).text()
544 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
545 menu
: { items
: items
},
548 widget
.paramInfo
= pi
;
549 $.extend( widget
, WidgetMethods
.tagWidget
);
551 widget
= new OO
.ui
.DropdownWidget( {
552 menu
: { items
: items
},
555 widget
.paramInfo
= pi
;
556 $.extend( widget
, WidgetMethods
.dropdownWidget
);
561 if ( !Array
.isArray( pi
.type
) ) {
562 throw new Error( 'Unknown parameter type ' + pi
.type
);
565 items
= pi
.type
.map( function ( v
) {
571 if ( pi
.deprecatedvalues
&& pi
.deprecatedvalues
.indexOf( v
) >= 0 ) {
572 config
.classes
.push( 'apihelp-deprecated-value' );
574 return new OO
.ui
.MenuOptionWidget( config
);
576 if ( Util
.apiBool( pi
.multi
) ) {
577 if ( pi
.allspecifier
!== undefined ) {
578 items
.unshift( new OO
.ui
.MenuOptionWidget( {
579 data
: pi
.allspecifier
,
580 label
: mw
.message( 'apisandbox-multivalue-all-values', pi
.allspecifier
).text()
584 widget
= new OO
.ui
.MenuTagMultiselectWidget( {
585 menu
: { items
: items
},
588 widget
.paramInfo
= pi
;
589 $.extend( widget
, WidgetMethods
.tagWidget
);
590 if ( Util
.apiBool( pi
.submodules
) ) {
591 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.multi
;
592 widget
.on( 'change', ApiSandbox
.updateUI
);
595 widget
= new OO
.ui
.DropdownWidget( {
596 menu
: { items
: items
},
599 widget
.paramInfo
= pi
;
600 $.extend( widget
, WidgetMethods
.dropdownWidget
);
601 if ( Util
.apiBool( pi
.submodules
) ) {
602 widget
.getSubmodules
= WidgetMethods
.submoduleWidget
.single
;
603 widget
.getMenu().on( 'select', ApiSandbox
.updateUI
);
605 if ( pi
.deprecatedvalues
) {
606 widget
.getMenu().on( 'select', function ( item
) {
607 this.$element
.toggleClass(
608 'apihelp-deprecated-value',
609 pi
.deprecatedvalues
.indexOf( item
.data
) >= 0
618 if ( Util
.apiBool( pi
.multi
) && multiModeAllowed
) {
619 innerWidget
= widget
;
621 multiModeButton
= new OO
.ui
.ButtonWidget( {
622 label
: mw
.message( 'apisandbox-add-multi' ).text()
624 $content
= innerWidget
.$element
.add( multiModeButton
.$element
);
626 widget
= new OO
.ui
.PopupTagMultiselectWidget( {
627 allowArbitrary
: true,
628 allowDuplicates
: Util
.apiBool( pi
.allowsduplicates
),
631 classes
: [ 'mw-apisandbox-popup' ],
636 widget
.paramInfo
= pi
;
637 $.extend( widget
, WidgetMethods
.tagWidget
);
640 if ( !innerWidget
.isDisabled() ) {
641 innerWidget
.apiCheckValid().done( function ( ok
) {
643 widget
.addTag( innerWidget
.getApiValue() );
644 innerWidget
.setApiValue( undefined );
651 if ( multiModeInput
) {
652 multiModeInput
.on( 'enter', func
);
654 multiModeButton
.on( 'click', func
);
657 if ( Util
.apiBool( pi
.required
) || opts
.nooptional
) {
658 finalWidget
= widget
;
660 finalWidget
= new OptionalWidget( widget
);
661 finalWidget
.paramInfo
= pi
;
662 $.extend( finalWidget
, WidgetMethods
.optionalWidget
);
663 if ( widget
.getSubmodules
) {
664 finalWidget
.getSubmodules
= widget
.getSubmodules
.bind( widget
);
665 finalWidget
.on( 'disable', function () { setTimeout( ApiSandbox
.updateUI
); } );
667 if ( widget
.getApiValueForTemplates
) {
668 finalWidget
.getApiValueForTemplates
= widget
.getApiValueForTemplates
.bind( widget
);
670 finalWidget
.setDisabled( true );
673 widget
.setApiValue( pi
[ 'default' ] );
679 * Parse an HTML string and call Util.fixupHTML()
681 * @param {string} html HTML to parse
684 parseHTML: function ( html
) {
685 var $ret
= $( $.parseHTML( html
) );
686 return Util
.fixupHTML( $ret
);
690 * Parse an i18n message and call Util.fixupHTML()
692 * @param {string} key Key of message to get
693 * @param {...Mixed} parameters Values for $N replacements
696 parseMsg: function () {
697 var $ret
= mw
.message
.apply( mw
.message
, arguments
).parseDom();
698 return Util
.fixupHTML( $ret
);
702 * Fix HTML for ApiSandbox display
705 * - Add target="_blank" to any links
707 * @param {jQuery} $html DOM to process
710 fixupHTML: function ( $html
) {
711 $html
.filter( 'a' ).add( $html
.find( 'a' ) )
712 .filter( '[href]:not([target])' )
713 .attr( 'target', '_blank' );
718 * Format a request and return a bunch of menu option widgets
720 * @param {Object} displayParams Query parameters, sanitized for display.
721 * @param {Object} rawParams Query parameters. You should probably use displayParams instead.
722 * @return {OO.ui.MenuOptionWidget[]} Each item's data should be an OO.ui.FieldLayout
724 formatRequest: function ( displayParams
, rawParams
) {
727 new OO
.ui
.MenuOptionWidget( {
728 label
: Util
.parseMsg( 'apisandbox-request-format-url-label' ),
729 data
: new OO
.ui
.FieldLayout(
730 new OO
.ui
.TextInputWidget( {
732 value
: mw
.util
.wikiScript( 'api' ) + '?' + $.param( displayParams
)
734 label
: Util
.parseMsg( 'apisandbox-request-url-label' )
738 new OO
.ui
.MenuOptionWidget( {
739 label
: Util
.parseMsg( 'apisandbox-request-format-json-label' ),
740 data
: new OO
.ui
.FieldLayout(
741 jsonInput
= new OO
.ui
.MultilineTextInputWidget( {
742 classes
: [ 'mw-apisandbox-textInputCode' ],
746 value
: JSON
.stringify( displayParams
, null, '\t' )
748 label
: Util
.parseMsg( 'apisandbox-request-json-label' )
750 ).on( 'toggle', function ( visible
) {
752 // Call updatePosition instead of adjustSize
753 // because the latter has weird caching
754 // behavior and the former bypasses it.
755 jsonInput
.updatePosition();
761 mw
.hook( 'apisandbox.formatRequest' ).fire( items
, displayParams
, rawParams
);
767 * Event handler for when formatDropdown's selection changes
769 onFormatDropdownChange: function () {
771 menu
= formatDropdown
.getMenu(),
772 items
= menu
.getItems(),
773 selectedField
= menu
.findSelectedItem() ? menu
.findSelectedItem().getData() : null;
775 for ( i
= 0; i
< items
.length
; i
++ ) {
776 items
[ i
].getData().toggle( items
[ i
].getData() === selectedField
);
782 * Interface to ApiSandbox UI
784 * @class mw.special.ApiSandbox
790 * Automatically called on $.ready()
795 $content
= $( '#mw-apisandbox' );
797 windowManager
= new OO
.ui
.WindowManager();
798 $( 'body' ).append( windowManager
.$element
);
799 windowManager
.addWindows( {
800 errorAlert
: new OO
.ui
.MessageDialog()
803 $toolbar
= $( '<div>' )
804 .addClass( 'mw-apisandbox-toolbar' )
806 new OO
.ui
.ButtonWidget( {
807 label
: mw
.message( 'apisandbox-submit' ).text(),
808 flags
: [ 'primary', 'progressive' ]
809 } ).on( 'click', ApiSandbox
.sendRequest
).$element
,
810 new OO
.ui
.ButtonWidget( {
811 label
: mw
.message( 'apisandbox-reset' ).text(),
813 } ).on( 'click', ApiSandbox
.resetUI
).$element
816 booklet
= new OO
.ui
.BookletLayout( {
822 panel
= new OO
.ui
.PanelLayout( {
823 classes
: [ 'mw-apisandbox-container' ],
824 content
: [ booklet
],
829 pages
.main
= new ApiSandbox
.PageLayout( { key
: 'main', path
: 'main' } );
831 // Parse the current hash string
832 if ( !ApiSandbox
.loadFromHash() ) {
833 ApiSandbox
.updateUI();
836 $( window
).on( 'hashchange', ApiSandbox
.loadFromHash
);
840 .append( $( '<p>' ).append( Util
.parseMsg( 'apisandbox-intro' ) ) )
842 $( '<div>' ).attr( 'id', 'mw-apisandbox-ui' )
844 .append( panel
.$element
)
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 ( !Object
.prototype.hasOwnProperty
.call( pages
, 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
,
972 checkPages
= [ pages
.main
];
974 // Blur any focused widget before submit, because
975 // OO.ui.ButtonWidget doesn't take focus itself (T128054)
976 $focus
= $( '#mw-apisandbox-ui' ).find( document
.activeElement
);
977 if ( $focus
.length
) {
981 suppressErrors
= false;
983 // save widget state in params (or load from it if we are forced)
984 if ( paramsAreForced
) {
985 ApiSandbox
.updateUI( params
);
988 while ( checkPages
.length
) {
989 page
= checkPages
.shift();
990 if ( page
.tokenWidget
) {
991 tokenWidgets
.push( page
.tokenWidget
);
993 deferreds
= deferreds
.concat( page
.apiCheckValid() );
994 page
.getQueryParams( params
, displayParams
);
995 subpages
= page
.getSubpages();
996 for ( i
= 0; i
< subpages
.length
; i
++ ) {
997 if ( Object
.prototype.hasOwnProperty
.call( pages
, subpages
[ i
].key
) ) {
998 checkPages
.push( pages
[ subpages
[ i
].key
] );
1003 if ( !paramsAreForced
) {
1004 // forced params means we are continuing a query; the base query should be preserved
1005 baseRequestParams
= $.extend( {}, params
);
1008 $.when
.apply( $, deferreds
).done( function () {
1009 var formatItems
, menu
, selectedLabel
, deferred
, actions
, errorCount
;
1011 // Count how many times `value` occurs in `array`.
1012 function countValues( value
, array
) {
1015 for ( i
= 0; i
< array
.length
; i
++ ) {
1016 if ( array
[ i
] === value
) {
1023 errorCount
= countValues( false, arguments
);
1024 if ( errorCount
> 0 ) {
1028 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1032 if ( tokenWidgets
.length
) {
1033 // Check all token widgets' validity separately
1034 deferred
= $.when
.apply( $, tokenWidgets
.map( function ( w
) {
1035 return w
.apiCheckValid();
1038 deferred
.done( function () {
1039 // If only the tokens are invalid, offer to fix them
1040 var tokenErrorCount
= countValues( false, arguments
);
1041 if ( tokenErrorCount
=== errorCount
) {
1042 delete actions
[ 0 ].flags
;
1045 label
: mw
.message( 'apisandbox-results-fixtoken' ).text(),
1051 deferred
= $.Deferred().resolve();
1053 deferred
.always( function () {
1054 windowManager
.openWindow( 'errorAlert', {
1055 title
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-title' ),
1056 message
: Util
.parseMsg( 'apisandbox-submit-invalid-fields-message' ),
1058 } ).closed
.then( function ( data
) {
1059 if ( data
&& data
.action
=== 'fix' ) {
1060 ApiSandbox
.fixTokenAndResend();
1067 query
= $.param( displayParams
);
1069 formatItems
= Util
.formatRequest( displayParams
, params
);
1071 // Force a 'fm' format with wrappedhtml=1, if available
1072 if ( params
.format
!== undefined ) {
1073 if ( Object
.prototype.hasOwnProperty
.call( availableFormats
, params
.format
+ 'fm' ) ) {
1074 params
.format
= params
.format
+ 'fm';
1076 if ( params
.format
.substr( -2 ) === 'fm' ) {
1077 params
.wrappedhtml
= 1;
1081 progressLoading
= false;
1082 $progressText
= $( '<span>' ).text( mw
.message( 'apisandbox-sending-request' ).text() );
1083 progress
= new OO
.ui
.ProgressBarWidget( {
1085 $content
: $progressText
1088 $result
= $( '<div>' )
1089 .append( progress
.$element
);
1091 resultPage
= page
= new OO
.ui
.PageLayout( '|results|', { expanded
: false } );
1092 page
.setupOutlineItem = function () {
1093 this.outlineItem
.setLabel( mw
.message( 'apisandbox-results' ).text() );
1096 if ( !formatDropdown
) {
1097 formatDropdown
= new OO
.ui
.DropdownWidget( {
1098 menu
: { items
: [] },
1101 formatDropdown
.getMenu().on( 'select', Util
.onFormatDropdownChange
);
1104 menu
= formatDropdown
.getMenu();
1105 selectedLabel
= menu
.findSelectedItem() ? menu
.findSelectedItem().getLabel() : '';
1106 if ( typeof selectedLabel
!== 'string' ) {
1107 selectedLabel
= selectedLabel
.text();
1109 menu
.clearItems().addItems( formatItems
);
1110 menu
.chooseItem( menu
.getItemFromLabel( selectedLabel
) || menu
.findFirstSelectableItem() );
1112 // Fire the event to update field visibilities
1113 Util
.onFormatDropdownChange();
1115 page
.$element
.empty()
1117 new OO
.ui
.FieldLayout(
1119 label
: Util
.parseMsg( 'apisandbox-request-selectformat-label' )
1122 formatItems
.map( function ( item
) {
1123 return item
.getData().$element
;
1127 ApiSandbox
.updateUI();
1128 booklet
.setPage( '|results|' );
1130 location
.href
= oldhash
= '#' + query
;
1133 contentType
: 'multipart/form-data',
1136 var xhr
= new window
.XMLHttpRequest();
1137 xhr
.upload
.addEventListener( 'progress', function ( e
) {
1138 if ( !progressLoading
) {
1139 if ( e
.lengthComputable
) {
1140 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1142 progress
.setProgress( false );
1146 xhr
.addEventListener( 'progress', function ( e
) {
1147 if ( !progressLoading
) {
1148 progressLoading
= true;
1149 $progressText
.text( mw
.message( 'apisandbox-loading-results' ).text() );
1151 if ( e
.lengthComputable
) {
1152 progress
.setProgress( e
.loaded
* 100 / e
.total
);
1154 progress
.setProgress( false );
1160 .catch( function ( code
, data
, result
, jqXHR
) {
1161 var deferred
= $.Deferred();
1163 if ( code
!== 'http' ) {
1164 // Not really an error, work around mw.Api thinking it is.
1165 deferred
.resolve( result
, jqXHR
);
1168 deferred
.reject
.apply( deferred
, arguments
);
1170 return deferred
.promise();
1172 .then( function ( data
, jqXHR
) {
1173 var m
, loadTime
, button
, clear
,
1174 ct
= jqXHR
.getResponseHeader( 'Content-Type' ),
1175 loginSuppressed
= jqXHR
.getResponseHeader( 'MediaWiki-Login-Suppressed' ) || 'false';
1178 if ( loginSuppressed
!== 'false' ) {
1180 .addClass( 'warning' )
1181 .append( Util
.parseMsg( 'apisandbox-results-login-suppressed' ) )
1182 .appendTo( $result
);
1184 if ( /^text\/mediawiki-api-prettyprint-wrapped(?:;|$)/.test( ct
) ) {
1185 data
= JSON
.parse( data
);
1186 if ( data
.modules
.length
) {
1187 mw
.loader
.load( data
.modules
);
1189 if ( data
.status
&& data
.status
!== 200 ) {
1191 .addClass( 'api-pretty-header api-pretty-status' )
1192 .append( Util
.parseMsg( 'api-format-prettyprint-status', data
.status
, data
.statustext
) )
1193 .appendTo( $result
);
1195 $result
.append( Util
.parseHTML( data
.html
) );
1196 loadTime
= data
.time
;
1197 } else if ( ( m
= data
.match( /<pre[ >][\s\S]*<\/pre>/ ) ) ) {
1198 $result
.append( Util
.parseHTML( m
[ 0 ] ) );
1199 if ( ( m
= data
.match( /"wgBackendResponseTime":\s*(\d+)/ ) ) ) {
1200 loadTime
= parseInt( m
[ 1 ], 10 );
1204 .addClass( 'api-pretty-content' )
1206 .appendTo( $result
);
1208 if ( paramsAreForced
|| data
[ 'continue' ] ) {
1210 $( '<div>' ).append(
1211 new OO
.ui
.ButtonWidget( {
1212 label
: mw
.message( 'apisandbox-continue' ).text()
1213 } ).on( 'click', function () {
1214 ApiSandbox
.sendRequest( $.extend( {}, baseRequestParams
, data
[ 'continue' ] ) );
1215 } ).setDisabled( !data
[ 'continue' ] ).$element
,
1216 ( clear
= new OO
.ui
.ButtonWidget( {
1217 label
: mw
.message( 'apisandbox-continue-clear' ).text()
1218 } ).on( 'click', function () {
1219 ApiSandbox
.updateUI( baseRequestParams
);
1220 clear
.setDisabled( true );
1221 booklet
.setPage( '|results|' );
1222 } ).setDisabled( !paramsAreForced
) ).$element
,
1223 new OO
.ui
.PopupButtonWidget( {
1228 $content
: $( '<div>' ).append( Util
.parseMsg( 'apisandbox-continue-help' ) ),
1236 if ( typeof loadTime
=== 'number' ) {
1238 $( '<div>' ).append(
1239 new OO
.ui
.LabelWidget( {
1240 label
: mw
.message( 'apisandbox-request-time', loadTime
).text()
1246 if ( jqXHR
.getResponseHeader( 'MediaWiki-API-Error' ) === 'badtoken' ) {
1247 // Flush all saved tokens in case one of them is the bad one.
1248 Util
.markTokensBad();
1249 button
= new OO
.ui
.ButtonWidget( {
1250 label
: mw
.message( 'apisandbox-results-fixtoken' ).text()
1252 button
.on( 'click', ApiSandbox
.fixTokenAndResend
)
1253 .on( 'click', button
.setDisabled
, [ true ], button
)
1254 .$element
.appendTo( $result
);
1256 }, function ( code
, data
) {
1257 var details
= 'HTTP error: ' + data
.exception
;
1260 new OO
.ui
.LabelWidget( {
1261 label
: mw
.message( 'apisandbox-results-error', details
).text(),
1262 classes
: [ 'error' ]
1270 * Handler for the "Correct token and resubmit" button
1272 * Used on a 'badtoken' error, it re-fetches token parameters for all
1273 * pages and then re-submits the query.
1275 fixTokenAndResend: function () {
1276 var page
, subpages
, i
, k
,
1278 tokenWait
= { dummy
: true },
1279 checkPages
= [ pages
.main
],
1280 success = function ( k
) {
1281 delete tokenWait
[ k
];
1282 if ( ok
&& $.isEmptyObject( tokenWait
) ) {
1283 ApiSandbox
.sendRequest();
1286 failure = function ( k
) {
1287 delete tokenWait
[ k
];
1291 while ( checkPages
.length
) {
1292 page
= checkPages
.shift();
1294 if ( page
.tokenWidget
) {
1295 k
= page
.apiModule
+ page
.tokenWidget
.paramInfo
.name
;
1296 tokenWait
[ k
] = page
.tokenWidget
.fetchToken();
1298 .done( success
.bind( page
.tokenWidget
, k
) )
1299 .fail( failure
.bind( page
.tokenWidget
, k
) );
1302 subpages
= page
.getSubpages();
1303 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1304 if ( Object
.prototype.hasOwnProperty
.call( pages
, subpages
[ i
].key
) ) {
1305 checkPages
.push( pages
[ subpages
[ i
].key
] );
1310 success( 'dummy', '' );
1314 * Reset validity indicators for all widgets
1316 updateValidityIndicators: function () {
1317 var page
, subpages
, i
,
1318 checkPages
= [ pages
.main
];
1320 while ( checkPages
.length
) {
1321 page
= checkPages
.shift();
1322 page
.apiCheckValid();
1323 subpages
= page
.getSubpages();
1324 for ( i
= 0; i
< subpages
.length
; i
++ ) {
1325 if ( Object
.prototype.hasOwnProperty
.call( pages
, subpages
[ i
].key
) ) {
1326 checkPages
.push( pages
[ subpages
[ i
].key
] );
1334 * PageLayout for API modules
1338 * @extends OO.ui.PageLayout
1340 * @param {Object} [config] Configuration options
1342 ApiSandbox
.PageLayout = function ( config
) {
1343 config
= $.extend( { prefix
: '', expanded
: false }, config
);
1344 this.displayText
= config
.key
;
1345 this.apiModule
= config
.path
;
1346 this.prefix
= config
.prefix
;
1347 this.paramInfo
= null;
1348 this.apiIsValid
= true;
1349 this.loadFromQueryParams
= null;
1351 this.itemsFieldset
= null;
1352 this.deprecatedItemsFieldset
= null;
1353 this.templatedItemsCache
= {};
1354 this.tokenWidget
= null;
1355 this.indentLevel
= config
.indentLevel
? config
.indentLevel
: 0;
1356 ApiSandbox
.PageLayout
[ 'super' ].call( this, config
.key
, config
);
1357 this.loadParamInfo();
1359 OO
.inheritClass( ApiSandbox
.PageLayout
, OO
.ui
.PageLayout
);
1360 ApiSandbox
.PageLayout
.prototype.setupOutlineItem = function () {
1361 this.outlineItem
.setLevel( this.indentLevel
);
1362 this.outlineItem
.setLabel( this.displayText
);
1363 this.outlineItem
.setIcon( this.apiIsValid
|| suppressErrors
? null : 'alert' );
1364 this.outlineItem
.setIconTitle(
1365 this.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
1369 function widgetLabelOnClick() {
1370 var f
= this.getField();
1371 if ( $.isFunction( f
.setDisabled
) ) {
1372 f
.setDisabled( false );
1374 if ( $.isFunction( f
.focus
) ) {
1380 * Create a widget and the FieldLayouts it needs
1382 * @param {Object} ppi API paraminfo data for the parameter
1383 * @param {string} name API parameter name
1385 * @return {OO.ui.Widget} return.widget
1386 * @return {OO.ui.FieldLayout} return.widgetField
1387 * @return {OO.ui.FieldLayout} return.helpField
1389 ApiSandbox
.PageLayout
.prototype.makeWidgetFieldLayouts = function ( ppi
, name
) {
1390 var j
, l
, widget
, descriptionContainer
, tmp
, flag
, count
, button
, widgetField
, helpField
, layoutConfig
;
1392 widget
= Util
.createWidgetForParameter( ppi
);
1393 if ( ppi
.tokentype
) {
1394 this.tokenWidget
= widget
;
1396 if ( this.paramInfo
.templatedparameters
.length
) {
1397 widget
.on( 'change', this.updateTemplatedParameters
, [ null ], this );
1400 descriptionContainer
= $( '<div>' );
1402 tmp
= Util
.parseHTML( ppi
.description
);
1403 tmp
.filter( 'dl' ).makeCollapsible( {
1405 } ).children( '.mw-collapsible-toggle' ).each( function () {
1406 var $this = $( this );
1407 $this.parent().prev( 'p' ).append( $this );
1409 descriptionContainer
.append( $( '<div>' ).addClass( 'description' ).append( tmp
) );
1411 if ( ppi
.info
&& ppi
.info
.length
) {
1412 for ( j
= 0; j
< ppi
.info
.length
; j
++ ) {
1413 descriptionContainer
.append( $( '<div>' )
1415 .append( Util
.parseHTML( ppi
.info
[ j
] ) )
1421 switch ( ppi
.type
) {
1424 count
= mw
.config
.get( 'wgFormattedNamespaces' ).length
;
1428 if ( ppi
.highmax
!== undefined ) {
1429 descriptionContainer
.append( $( '<div>' )
1433 'api-help-param-limit2', ppi
.max
, ppi
.highmax
1436 Util
.parseMsg( 'apisandbox-param-limit' )
1440 descriptionContainer
.append( $( '<div>' )
1443 Util
.parseMsg( 'api-help-param-limit', ppi
.max
),
1445 Util
.parseMsg( 'apisandbox-param-limit' )
1453 if ( ppi
.min
!== undefined ) {
1456 if ( ppi
.max
!== undefined ) {
1460 descriptionContainer
.append( $( '<div>' )
1462 .append( Util
.parseMsg(
1463 'api-help-param-integer-' + tmp
,
1464 Util
.apiBool( ppi
.multi
) ? 2 : 1,
1472 if ( Array
.isArray( ppi
.type
) ) {
1474 count
= ppi
.type
.length
;
1478 if ( Util
.apiBool( ppi
.multi
) ) {
1480 if ( flag
&& !( widget
instanceof OO
.ui
.TagMultiselectWidget
) &&
1482 widget
instanceof OptionalWidget
&&
1483 widget
.widget
instanceof OO
.ui
.TagMultiselectWidget
1486 tmp
.push( mw
.message( 'api-help-param-multi-separate' ).parse() );
1488 if ( count
> ppi
.lowlimit
) {
1490 mw
.message( 'api-help-param-multi-max', ppi
.lowlimit
, ppi
.highlimit
).parse()
1494 descriptionContainer
.append( $( '<div>' )
1496 .append( Util
.parseHTML( tmp
.join( ' ' ) ) )
1500 if ( 'maxbytes' in ppi
) {
1501 descriptionContainer
.append( $( '<div>' )
1503 .append( Util
.parseMsg( 'api-help-param-maxbytes', ppi
.maxbytes
) )
1506 if ( 'maxchars' in ppi
) {
1507 descriptionContainer
.append( $( '<div>' )
1509 .append( Util
.parseMsg( 'api-help-param-maxchars', ppi
.maxchars
) )
1512 if ( ppi
.usedTemplateVars
&& ppi
.usedTemplateVars
.length
) {
1514 for ( j
= 0, l
= ppi
.usedTemplateVars
.length
; j
< l
; j
++ ) {
1515 tmp
= tmp
.add( $( '<var>' ).text( ppi
.usedTemplateVars
[ j
] ) );
1516 if ( j
=== l
- 2 ) {
1517 tmp
= tmp
.add( mw
.message( 'and' ).parseDom() );
1518 tmp
= tmp
.add( mw
.message( 'word-separator' ).parseDom() );
1519 } else if ( j
!== l
- 1 ) {
1520 tmp
= tmp
.add( mw
.message( 'comma-separator' ).parseDom() );
1523 descriptionContainer
.append( $( '<div>' )
1525 .append( Util
.parseMsg(
1526 'apisandbox-templated-parameter-reason',
1527 ppi
.usedTemplateVars
.length
,
1533 helpField
= new OO
.ui
.FieldLayout(
1536 classes
: [ 'mw-apisandbox-spacer' ]
1539 classes
: [ 'mw-apisandbox-help-field' ],
1540 label
: descriptionContainer
1546 classes
: [ 'mw-apisandbox-widget-field' ],
1550 if ( ppi
.tokentype
) {
1551 button
= new OO
.ui
.ButtonWidget( {
1552 label
: mw
.message( 'apisandbox-fetch-token' ).text()
1554 button
.on( 'click', widget
.fetchToken
, [], widget
);
1556 widgetField
= new OO
.ui
.ActionFieldLayout( widget
, button
, layoutConfig
);
1558 widgetField
= new OO
.ui
.FieldLayout( widget
, layoutConfig
);
1561 // We need our own click handler on the widget label to
1562 // turn off the disablement.
1563 widgetField
.$label
.on( 'click', widgetLabelOnClick
.bind( widgetField
) );
1565 // Don't grey out the label when the field is disabled,
1566 // it makes it too hard to read and our "disabled"
1567 // isn't really disabled.
1568 widgetField
.onFieldDisable( false );
1569 widgetField
.onFieldDisable
= $.noop
;
1571 widgetField
.apiParamIndex
= ppi
.index
;
1575 widgetField
: widgetField
,
1576 helpField
: helpField
1581 * Update templated parameters in the page
1583 * @param {Object} [params] Query parameters for initializing the widgets
1585 ApiSandbox
.PageLayout
.prototype.updateTemplatedParameters = function ( params
) {
1586 var p
, toProcess
, doProcess
, tmp
, toRemove
,
1588 pi
= this.paramInfo
,
1589 prefix
= that
.prefix
+ pi
.prefix
;
1591 if ( !pi
|| !pi
.templatedparameters
.length
) {
1595 if ( !$.isPlainObject( params
) ) {
1600 $.each( this.templatedItemsCache
, function ( k
, el
) {
1601 if ( el
.widget
.isElementAttached() ) {
1606 // This bit duplicates the PHP logic in ApiBase::extractRequestParams().
1607 // If you update this, see if that needs updating too.
1608 toProcess
= pi
.templatedparameters
.map( function ( p
) {
1610 name
: prefix
+ p
.name
,
1612 vars
: $.extend( {}, p
.templatevars
),
1616 doProcess = function ( placeholder
, target
) {
1617 var values
, container
, index
, usedVars
, done
;
1619 target
= prefix
+ target
;
1621 if ( !that
.widgets
[ target
] ) {
1622 // The target wasn't processed yet, try the next one.
1623 // If all hit this case, the parameter has no expansions.
1627 if ( !that
.widgets
[ target
].getApiValueForTemplates
) {
1628 // Not a multi-valued widget, so it can't have expansions.
1632 values
= that
.widgets
[ target
].getApiValueForTemplates();
1633 if ( !Array
.isArray( values
) || !values
.length
) {
1634 // The target was processed but has no (valid) values.
1635 // That means it has no expansions.
1639 // Expand this target in the name and all other targets,
1640 // then requeue if there are more targets left or create the widget
1641 // and add it to the form if all are done.
1642 delete p
.vars
[ placeholder
];
1643 usedVars
= p
.usedVars
.concat( [ target
] );
1644 placeholder
= '{' + placeholder
+ '}';
1645 done
= $.isEmptyObject( p
.vars
);
1647 container
= Util
.apiBool( p
.info
.deprecated
) ? that
.deprecatedItemsFieldset
: that
.itemsFieldset
;
1648 index
= container
.getItems().findIndex( function ( el
) {
1649 return el
.apiParamIndex
!== undefined && el
.apiParamIndex
> p
.info
.index
;
1655 values
.forEach( function ( value
) {
1658 if ( !/^[^{}]*$/.exec( value
) ) {
1659 // Skip values that make invalid parameter names
1663 name
= p
.name
.replace( placeholder
, value
);
1665 if ( that
.templatedItemsCache
[ name
] ) {
1666 tmp
= that
.templatedItemsCache
[ name
];
1668 tmp
= that
.makeWidgetFieldLayouts(
1669 $.extend( {}, p
.info
, { usedTemplateVars
: usedVars
} ), name
1671 that
.templatedItemsCache
[ name
] = tmp
;
1673 delete toRemove
[ name
];
1674 if ( !tmp
.widget
.isElementAttached() ) {
1675 that
.widgets
[ name
] = tmp
.widget
;
1676 container
.addItems( [ tmp
.widgetField
, tmp
.helpField
], index
);
1677 if ( index
!== undefined ) {
1682 tmp
.widget
.setApiValue( Object
.prototype.hasOwnProperty
.call( params
, name
) ? params
[ name
] : undefined );
1686 $.each( p
.vars
, function ( k
, v
) {
1687 newVars
[ k
] = v
.replace( placeholder
, value
);
1699 while ( toProcess
.length
) {
1700 p
= toProcess
.shift();
1701 $.each( p
.vars
, doProcess
);
1704 toRemove
= $.map( toRemove
, function ( el
, name
) {
1705 delete that
.widgets
[ name
];
1706 return [ el
.widgetField
, el
.helpField
];
1708 if ( toRemove
.length
) {
1709 this.itemsFieldset
.removeItems( toRemove
);
1710 this.deprecatedItemsFieldset
.removeItems( toRemove
);
1715 * Fetch module information for this page's module, then create UI
1717 ApiSandbox
.PageLayout
.prototype.loadParamInfo = function () {
1718 var dynamicFieldset
, dynamicParamNameWidget
,
1720 removeDynamicParamWidget = function ( name
, layout
) {
1721 dynamicFieldset
.removeItems( [ layout
] );
1722 delete that
.widgets
[ name
];
1724 addDynamicParamWidget = function () {
1725 var name
, layout
, widget
, button
;
1727 // Check name is filled in
1728 name
= dynamicParamNameWidget
.getValue().trim();
1729 if ( name
=== '' ) {
1730 dynamicParamNameWidget
.focus();
1734 if ( that
.widgets
[ name
] !== undefined ) {
1735 windowManager
.openWindow( 'errorAlert', {
1736 title
: Util
.parseMsg( 'apisandbox-dynamic-error-exists', name
),
1740 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' ),
1748 widget
= Util
.createWidgetForParameter( {
1755 button
= new OO
.ui
.ButtonWidget( {
1757 flags
: 'destructive'
1759 layout
= new OO
.ui
.ActionFieldLayout(
1767 button
.on( 'click', removeDynamicParamWidget
, [ name
, layout
] );
1768 that
.widgets
[ name
] = widget
;
1769 dynamicFieldset
.addItems( [ layout
], dynamicFieldset
.getItems().length
- 1 );
1772 dynamicParamNameWidget
.setValue( '' );
1775 this.$element
.empty()
1776 .append( new OO
.ui
.ProgressBarWidget( {
1778 text
: mw
.message( 'apisandbox-loading', this.displayText
).text()
1781 Util
.fetchModuleInfo( this.apiModule
)
1782 .done( function ( pi
) {
1783 var prefix
, i
, j
, tmp
,
1785 deprecatedItems
= [],
1787 filterFmModules = function ( v
) {
1788 return v
.substr( -2 ) !== 'fm' ||
1789 !Object
.prototype.hasOwnProperty
.call( availableFormats
, v
.substr( 0, v
.length
- 2 ) );
1792 // This is something of a hack. We always want the 'format' and
1793 // 'action' parameters from the main module to be specified,
1794 // and for 'format' we also want to simplify the dropdown since
1795 // we always send the 'fm' variant.
1796 if ( that
.apiModule
=== 'main' ) {
1797 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1798 if ( pi
.parameters
[ i
].name
=== 'action' ) {
1799 pi
.parameters
[ i
].required
= true;
1800 delete pi
.parameters
[ i
][ 'default' ];
1802 if ( pi
.parameters
[ i
].name
=== 'format' ) {
1803 tmp
= pi
.parameters
[ i
].type
;
1804 for ( j
= 0; j
< tmp
.length
; j
++ ) {
1805 availableFormats
[ tmp
[ j
] ] = true;
1807 pi
.parameters
[ i
].type
= tmp
.filter( filterFmModules
);
1808 pi
.parameters
[ i
][ 'default' ] = 'json';
1809 pi
.parameters
[ i
].required
= true;
1814 // Hide the 'wrappedhtml' parameter on format modules
1815 if ( pi
.group
=== 'format' ) {
1816 pi
.parameters
= pi
.parameters
.filter( function ( p
) {
1817 return p
.name
!== 'wrappedhtml';
1821 that
.paramInfo
= pi
;
1823 items
.push( new OO
.ui
.FieldLayout(
1824 new OO
.ui
.Widget( {} ).toggle( false ), {
1826 label
: Util
.parseHTML( pi
.description
)
1830 if ( pi
.helpurls
.length
) {
1831 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1833 label
: mw
.message( 'apisandbox-helpurls' ).text(),
1838 $content
: $( '<ul>' ).append( pi
.helpurls
.map( function ( link
) {
1839 return $( '<li>' ).append( $( '<a>' )
1840 .attr( { href
: link
, target
: '_blank' } )
1848 if ( pi
.examples
.length
) {
1849 buttons
.push( new OO
.ui
.PopupButtonWidget( {
1851 label
: mw
.message( 'apisandbox-examples' ).text(),
1856 $content
: $( '<ul>' ).append( pi
.examples
.map( function ( example
) {
1858 .attr( 'href', '#' + example
.query
)
1859 .html( example
.description
);
1860 a
.find( 'a' ).contents().unwrap(); // Can't nest links
1861 return $( '<li>' ).append( a
);
1867 if ( buttons
.length
) {
1868 items
.push( new OO
.ui
.FieldLayout(
1869 new OO
.ui
.ButtonGroupWidget( {
1871 } ), { align
: 'top' }
1875 if ( pi
.parameters
.length
) {
1876 prefix
= that
.prefix
+ pi
.prefix
;
1877 for ( i
= 0; i
< pi
.parameters
.length
; i
++ ) {
1878 tmp
= that
.makeWidgetFieldLayouts( pi
.parameters
[ i
], prefix
+ pi
.parameters
[ i
].name
);
1879 that
.widgets
[ prefix
+ pi
.parameters
[ i
].name
] = tmp
.widget
;
1880 if ( Util
.apiBool( pi
.parameters
[ i
].deprecated
) ) {
1881 deprecatedItems
.push( tmp
.widgetField
, tmp
.helpField
);
1883 items
.push( tmp
.widgetField
, tmp
.helpField
);
1888 if ( !pi
.parameters
.length
&& !Util
.apiBool( pi
.dynamicparameters
) ) {
1889 items
.push( new OO
.ui
.FieldLayout(
1890 new OO
.ui
.Widget( {} ).toggle( false ), {
1892 label
: Util
.parseMsg( 'apisandbox-no-parameters' )
1897 that
.$element
.empty();
1899 that
.itemsFieldset
= new OO
.ui
.FieldsetLayout( {
1900 label
: that
.displayText
1902 that
.itemsFieldset
.addItems( items
);
1903 that
.itemsFieldset
.$element
.appendTo( that
.$element
);
1905 if ( Util
.apiBool( pi
.dynamicparameters
) ) {
1906 dynamicFieldset
= new OO
.ui
.FieldsetLayout();
1907 dynamicParamNameWidget
= new OO
.ui
.TextInputWidget( {
1908 placeholder
: mw
.message( 'apisandbox-dynamic-parameters-add-placeholder' ).text()
1909 } ).on( 'enter', addDynamicParamWidget
);
1910 dynamicFieldset
.addItems( [
1911 new OO
.ui
.FieldLayout(
1912 new OO
.ui
.Widget( {} ).toggle( false ), {
1914 label
: Util
.parseHTML( pi
.dynamicparameters
)
1917 new OO
.ui
.ActionFieldLayout(
1918 dynamicParamNameWidget
,
1919 new OO
.ui
.ButtonWidget( {
1921 flags
: 'progressive'
1922 } ).on( 'click', addDynamicParamWidget
),
1924 label
: mw
.message( 'apisandbox-dynamic-parameters-add-label' ).text(),
1931 $( '<legend>' ).text( mw
.message( 'apisandbox-dynamic-parameters' ).text() ),
1932 dynamicFieldset
.$element
1934 .appendTo( that
.$element
);
1937 that
.deprecatedItemsFieldset
= new OO
.ui
.FieldsetLayout().addItems( deprecatedItems
).toggle( false );
1938 tmp
= $( '<fieldset>' )
1939 .toggle( !that
.deprecatedItemsFieldset
.isEmpty() )
1941 $( '<legend>' ).append(
1942 new OO
.ui
.ToggleButtonWidget( {
1943 label
: mw
.message( 'apisandbox-deprecated-parameters' ).text()
1944 } ).on( 'change', that
.deprecatedItemsFieldset
.toggle
, [], that
.deprecatedItemsFieldset
).$element
1946 that
.deprecatedItemsFieldset
.$element
1948 .appendTo( that
.$element
);
1949 that
.deprecatedItemsFieldset
.on( 'add', function () {
1950 this.toggle( !that
.deprecatedItemsFieldset
.isEmpty() );
1952 that
.deprecatedItemsFieldset
.on( 'remove', function () {
1953 this.toggle( !that
.deprecatedItemsFieldset
.isEmpty() );
1956 // Load stored params, if any, then update the booklet if we
1957 // have subpages (or else just update our valid-indicator).
1958 tmp
= that
.loadFromQueryParams
;
1959 that
.loadFromQueryParams
= null;
1960 if ( $.isPlainObject( tmp
) ) {
1961 that
.loadQueryParams( tmp
);
1963 that
.updateTemplatedParameters();
1965 if ( that
.getSubpages().length
> 0 ) {
1966 ApiSandbox
.updateUI( tmp
);
1968 that
.apiCheckValid();
1970 } ).fail( function ( code
, detail
) {
1971 that
.$element
.empty()
1973 new OO
.ui
.LabelWidget( {
1974 label
: mw
.message( 'apisandbox-load-error', that
.apiModule
, detail
).text(),
1975 classes
: [ 'error' ]
1977 new OO
.ui
.ButtonWidget( {
1978 label
: mw
.message( 'apisandbox-retry' ).text()
1979 } ).on( 'click', that
.loadParamInfo
, [], that
).$element
1985 * Check that all widgets on the page are in a valid state.
1987 * @return {jQuery.Promise[]} One promise for each widget, resolved with `false` if invalid
1989 ApiSandbox
.PageLayout
.prototype.apiCheckValid = function () {
1990 var promises
, that
= this;
1992 if ( this.paramInfo
=== null ) {
1995 promises
= $.map( this.widgets
, function ( widget
) {
1996 return widget
.apiCheckValid();
1998 $.when
.apply( $, promises
).then( function () {
1999 that
.apiIsValid
= $.inArray( false, arguments
) === -1;
2000 if ( that
.getOutlineItem() ) {
2001 that
.getOutlineItem().setIcon( that
.apiIsValid
|| suppressErrors
? null : 'alert' );
2002 that
.getOutlineItem().setIconTitle(
2003 that
.apiIsValid
|| suppressErrors
? '' : mw
.message( 'apisandbox-alert-page' ).plain()
2012 * Load form fields from query parameters
2014 * @param {Object} params
2016 ApiSandbox
.PageLayout
.prototype.loadQueryParams = function ( params
) {
2017 if ( this.paramInfo
=== null ) {
2018 this.loadFromQueryParams
= params
;
2020 $.each( this.widgets
, function ( name
, widget
) {
2021 var v
= Object
.prototype.hasOwnProperty
.call( params
, name
) ? params
[ name
] : undefined;
2022 widget
.setApiValue( v
);
2024 this.updateTemplatedParameters( params
);
2029 * Load query params from form fields
2031 * @param {Object} params Write query parameters into this object
2032 * @param {Object} displayParams Write query parameters for display into this object
2034 ApiSandbox
.PageLayout
.prototype.getQueryParams = function ( params
, displayParams
) {
2035 $.each( this.widgets
, function ( name
, widget
) {
2036 var value
= widget
.getApiValue();
2037 if ( value
!== undefined ) {
2038 params
[ name
] = value
;
2039 if ( $.isFunction( widget
.getApiValueForDisplay
) ) {
2040 value
= widget
.getApiValueForDisplay();
2042 displayParams
[ name
] = value
;
2048 * Fetch a list of subpage names loaded by this page
2052 ApiSandbox
.PageLayout
.prototype.getSubpages = function () {
2054 $.each( this.widgets
, function ( name
, widget
) {
2056 if ( $.isFunction( widget
.getSubmodules
) ) {
2057 submodules
= widget
.getSubmodules();
2058 for ( i
= 0; i
< submodules
.length
; i
++ ) {
2060 key
: name
+ '=' + submodules
[ i
].value
,
2061 path
: submodules
[ i
].path
,
2062 prefix
: widget
.paramInfo
.submoduleparamprefix
|| ''
2070 $( ApiSandbox
.init
);
2072 module
.exports
= ApiSandbox
;
2074 }( jQuery
, mediaWiki
, OO
) );