Merge "Add tests for WikiMap and WikiReference"
[lhc/web/wiklou.git] / resources / src / mediawiki.api / mediawiki.api.options.js
1 /**
2 * @class mw.Api.plugin.options
3 */
4 ( function ( mw, $ ) {
5
6 $.extend( mw.Api.prototype, {
7
8 /**
9 * Asynchronously save the value of a single user option using the API. See #saveOptions.
10 *
11 * @param {string} name
12 * @param {string|null} value
13 * @return {jQuery.Promise}
14 */
15 saveOption: function ( name, value ) {
16 var param = {};
17 param[ name ] = value;
18 return this.saveOptions( param );
19 },
20
21 /**
22 * Asynchronously save the values of user options using the API.
23 *
24 * If a value of `null` is provided, the given option will be reset to the default value.
25 *
26 * Any warnings returned by the API, including warnings about invalid option names or values,
27 * are ignored. However, do not rely on this behavior.
28 *
29 * If necessary, the options will be saved using several parallel API requests. Only one promise
30 * is always returned that will be resolved when all requests complete.
31 *
32 * @param {Object} options Options as a `{ name: value, … }` object
33 * @return {jQuery.Promise}
34 */
35 saveOptions: function ( options ) {
36 var name, value, bundleable,
37 grouped = [],
38 deferreds = [];
39
40 for ( name in options ) {
41 value = options[ name ] === null ? null : String( options[ name ] );
42
43 // Can we bundle this option, or does it need a separate request?
44 bundleable =
45 ( value === null || value.indexOf( '|' ) === -1 ) &&
46 ( name.indexOf( '|' ) === -1 && name.indexOf( '=' ) === -1 );
47
48 if ( bundleable ) {
49 if ( value !== null ) {
50 grouped.push( name + '=' + value );
51 } else {
52 // Omitting value resets the option
53 grouped.push( name );
54 }
55 } else {
56 if ( value !== null ) {
57 deferreds.push( this.postWithToken( 'options', {
58 action: 'options',
59 optionname: name,
60 optionvalue: value
61 } ) );
62 } else {
63 // Omitting value resets the option
64 deferreds.push( this.postWithToken( 'options', {
65 action: 'options',
66 optionname: name
67 } ) );
68 }
69 }
70 }
71
72 if ( grouped.length ) {
73 deferreds.push( this.postWithToken( 'options', {
74 action: 'options',
75 change: grouped.join( '|' )
76 } ) );
77 }
78
79 return $.when.apply( $, deferreds );
80 }
81
82 } );
83
84 /**
85 * @class mw.Api
86 * @mixins mw.Api.plugin.options
87 */
88
89 }( mediaWiki, jQuery ) );