2 * JavaScript backwards-compatibility alternatives and other convenience functions
6 trimLeft : function( str
) {
7 return str
=== null ? '' : str
.toString().replace( /^\s+/, '' );
9 trimRight : function( str
) {
11 '' : str
.toString().replace( /\s+$/, '' );
13 ucFirst : function( str
) {
14 return str
.substr( 0, 1 ).toUpperCase() + str
.substr( 1 );
16 escapeRE : function( str
) {
17 return str
.replace ( /([\\{}()|.?*+\-^$\[\]])/g, "\\$1" );
19 isDomElement : function( el
) {
20 return !!el
&& !!el
.nodeType
;
22 isEmpty : function( v
) {
24 if ( v
=== "" || v
=== 0 || v
=== "0" || v
=== null
25 || v
=== false || typeof v
=== 'undefined' )
29 // the for-loop could potentially contain prototypes
30 // to avoid that we check it's length first
31 if ( v
.length
=== 0 ) {
34 if ( typeof v
=== 'object' ) {
42 compareArray : function( arrThis
, arrAgainst
) {
43 if ( arrThis
.length
!= arrAgainst
.length
) {
46 for ( var i
= 0; i
< arrThis
.length
; i
++ ) {
47 if ( arrThis
[i
] instanceof Array
) {
48 if ( !$.compareArray( arrThis
[i
], arrAgainst
[i
] ) ) {
51 } else if ( arrThis
[i
] !== arrAgainst
[i
] ) {
57 compareObject : function( objectA
, objectB
) {
59 // Do a simple check if the types match
60 if ( typeof objectA
== typeof objectB
) {
62 // Only loop over the contents if it really is an object
63 if ( typeof objectA
== 'object' ) {
64 // If they are aliases of the same object (ie. mw and mediaWiki) return now
65 if ( objectA
=== objectB
) {
69 // Iterate over each property
70 for ( prop
in objectA
) {
71 // Check if this property is also present in the other object
72 if ( prop
in objectB
) {
73 // Compare the types of the properties
74 var type
= typeof objectA
[prop
];
75 if ( type
== typeof objectB
[prop
] ) {
76 // Recursively check objects inside this one
79 if ( !$.compareObject( objectA
[prop
], objectB
[prop
] ) ) {
84 // Functions need to be strings to compare them properly
85 if ( objectA
[prop
].toString() !== objectB
[prop
].toString() ) {
91 if ( objectA
[prop
] !== objectB
[prop
] ) {
103 // Check for properties in B but not in A
104 // This is about 15% faster (tested in Safari 5 and Firefox 3.6)
105 // ...than incrementing a count variable in the above and below loops
106 // See also: http://www.mediawiki.org/wiki/ResourceLoader/Default_modules/compareObject_test#Results
107 for ( prop
in objectB
) {
108 if ( !( prop
in objectA
) ) {
122 * Core MediaWiki JavaScript Library
126 window
.mediaWiki
= new ( function( $ ) {
130 /* Private Members */
132 // List of messages that have been requested to be loaded
133 var messageQueue
= {};
138 * An object which allows single and multiple get/set/exists functionality
139 * on a list of key / value pairs.
141 * @param {boolean} global Whether to get/set/exists values on the window
142 * object or a private object
144 function Map( global
) {
145 this.values
= ( global
=== true ) ? window
: {};
149 * Gets the value of a key, or a list of key/value pairs for an array of keys.
151 * If called with no arguments, all values will be returned.
153 * @param selection mixed Key or array of keys to get values for
154 * @param fallback mixed Value to use in case key(s) do not exist (optional)
156 Map
.prototype.get = function( selection
, fallback
) {
157 if ( typeof selection
=== 'object' ) {
158 selection
= $.makeArray( selection
);
160 for ( var i
= 0; i
< selection
.length
; i
++ ) {
161 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
164 } else if ( typeof selection
=== 'string' ) {
165 if ( typeof this.values
[selection
] === 'undefined' ) {
166 if ( typeof fallback
!== 'undefined' ) {
171 return this.values
[selection
];
177 * Sets one or multiple key/value pairs.
179 * @param selection mixed Key or object of key/value pairs to set
180 * @param value mixed Value to set (optional, only in use when key is a string)
182 Map
.prototype.set = function( selection
, value
) {
183 if ( typeof selection
=== 'object' ) {
184 for ( var s
in selection
) {
185 this.values
[s
] = selection
[s
];
188 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
189 this.values
[selection
] = value
;
196 * Checks if one or multiple keys exist.
198 * @param selection mixed Key or array of keys to check
199 * @return boolean Existence of key(s)
201 Map
.prototype.exists = function( selection
) {
202 if ( typeof selection
=== 'object' ) {
203 for ( var s
= 0; s
< selection
.length
; s
++ ) {
204 if ( !( selection
[s
] in this.values
) ) {
210 return selection
in this.values
;
215 * Message object, similar to Message in PHP
217 function Message( map
, key
, parameters
) {
218 this.format
= 'parse';
221 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
225 * Appends parameters for replacement
227 * @param parameters mixed First in a list of variadic arguments to append as message parameters
229 Message
.prototype.params = function( parameters
) {
230 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
231 this.parameters
[this.parameters
.length
] = parameters
[i
];
237 * Converts message object to it's string form based on the state of format
239 * @return {string} String form of message
241 Message
.prototype.toString = function() {
242 if ( !this.map
.exists( this.key
) ) {
243 // Return <key> if key does not exist
244 return '<' + this.key
+ '>';
246 var text
= this.map
.get( this.key
);
247 var parameters
= this.parameters
;
248 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
249 var index
= parseInt( match
, 10 ) - 1;
250 return index
in parameters
? parameters
[index
] : '$' + match
;
253 if ( this.format
=== 'plain' ) {
256 if ( this.format
=== 'escaped' ) {
257 // According to Message.php this needs {{-transformation, which is
259 return mw
.html
.escape( text
);
262 /* This should be fixed up when we have a parser
263 if ( this.format === 'parse' && 'language' in mediaWiki ) {
264 text = mw.language.parse( text );
271 * Changes format to parse and converts message to string
273 * @return {string} String form of parsed message
275 Message
.prototype.parse = function() {
276 this.format
= 'parse';
277 return this.toString();
281 * Changes format to plain and converts message to string
283 * @return {string} String form of plain message
285 Message
.prototype.plain = function() {
286 this.format
= 'plain';
287 return this.toString();
291 * Changes the format to html escaped and converts message to string
293 * @return {string} String form of html escaped message
295 Message
.prototype.escaped = function() {
296 this.format
= 'escaped';
297 return this.toString();
301 * Checks if message exists
303 * @return {string} String form of parsed message
305 Message
.prototype.exists = function() {
306 return this.map
.exists( this.key
);
314 /* Private Members */
320 this.options
= new Map();
325 * Generates a random user session ID (32 alpha-numeric characters).
327 * This information would potentially be stored in a cookie to identify a user during a
328 * session or series of sessions. It's uniqueness should not be depended on.
330 * @return string random set of 32 alpha-numeric characters
332 function generateId() {
334 var seed
= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
335 for ( var i
= 0, r
; i
< 32; i
++ ) {
336 r
= Math
.floor( Math
.random() * seed
.length
);
337 id
+= seed
.substring( r
, r
+ 1 );
343 * Gets the current user's name.
345 * @return mixed user name string or null if users is anonymous
347 this.name = function() {
348 return mw
.config
.get( 'wgUserName' );
352 * Checks if the current user is anonymous.
356 this.anonymous = function() {
357 return that
.name() ? false : true;
361 * Gets a random session ID automatically generated and kept in a cookie.
363 * This ID is ephemeral for everyone, staying in their browser only until they close
366 * Do not use this method before the first call to mw.loader.go(), it depends on
367 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
368 * won't be loaded until the first call to go().
370 * @return string user name or random session ID
372 this.sessionId = function () {
373 var sessionId
= $.cookie( 'mediaWiki.user.sessionId' );
374 if ( typeof sessionId
== 'undefined' || sessionId
=== null ) {
375 sessionId
= generateId();
376 $.cookie( 'mediaWiki.user.sessionId', sessionId
, { 'expires': null, 'path': '/' } );
382 * Gets the current user's name or a random ID automatically generated and kept in a cookie.
384 * This ID is persistent for anonymous users, staying in their browser up to 1 year. The
385 * expiration time is reset each time the ID is queried, so in most cases this ID will
386 * persist until the browser's cookies are cleared or the user doesn't visit for 1 year.
388 * Do not use this method before the first call to mw.loader.go(), it depends on
389 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
390 * won't be loaded until the first call to go().
392 * @return string user name or random session ID
394 this.id = function() {
395 var name
= that
.name();
399 var id
= $.cookie( 'mediaWiki.user.id' );
400 if ( typeof id
== 'undefined' || id
=== null ) {
403 // Set cookie if not set, or renew it if already set
404 $.cookie( 'mediaWiki.user.id', id
, { 'expires': 365, 'path': '/' } );
409 * Gets the user's bucket, placing them in one at random based on set odds if needed.
411 * @param key String: Name of bucket
412 * @param options Object: Bucket configuration options
413 * @param options.buckets Object: List of bucket-name/relative-probability pairs (required,
414 * must have at least one pair)
415 * @param options.version Number: Version of bucket test, changing this forces rebucketing
416 * (optional, default: 0)
417 * @param options.tracked Boolean: Track the event of bucketing through the API module of
418 * the ClickTracking extension (optional, default: false)
419 * @param options.expires Number: Length of time (in days) until the user gets rebucketed
420 * (optional, default: 30)
421 * @return String: Bucket name - the randomly chosen key of the options.buckets object
424 * mw.user.bucket( 'test', {
425 * 'buckets': { 'ignored': 50, 'control': 25, 'test': 25 },
431 this.bucket = function( key
, options
) {
432 options
= $.extend( {
438 var cookie
= $.cookie( 'mediaWiki.user.bucket:' + key
);
441 // Bucket information is stored as 2 integers, together as version:bucket like: "1:2"
442 if ( typeof cookie
=== 'string' && cookie
.length
> 2 && cookie
.indexOf( ':' ) > 0 ) {
443 var parts
= cookie
.split( ':' );
444 if ( parts
.length
> 1 && parts
[0] == options
.version
) {
445 version
= Number( parts
[0] );
446 bucket
= String( parts
[1] );
449 if ( bucket
=== null ) {
450 if ( !$.isPlainObject( options
.buckets
) ) {
451 throw 'Invalid buckets error. Object expected for options.buckets.';
453 version
= Number( options
.version
);
456 for ( k
in options
.buckets
) {
457 range
+= options
.buckets
[k
];
459 // Select random value within range
460 var rand
= Math
.random() * range
;
461 // Determine which bucket the value landed in
463 for ( k
in options
.buckets
) {
465 total
+= options
.buckets
[k
];
466 if ( total
>= rand
) {
470 if ( options
.tracked
) {
471 mw
.loader
.using( 'jquery.clickTracking', function() {
473 'mediaWiki.user.bucket:' + key
+ '@' + version
+ ':' + bucket
478 'mediaWiki.user.bucket:' + key
,
479 version
+ ':' + bucket
,
480 { 'path': '/', 'expires': Number( options
.expires
) }
490 * Dummy function which in debug mode can be replaced with a function that
491 * does something clever
493 this.log = function() { };
496 * Make the Map-class publicly available
501 * List of configuration values
503 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
504 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
505 * in the global window object.
510 * Information about the current user
512 this.user
= new User();
515 * Localization system
517 this.messages
= new this.Map();
522 * Gets a message object, similar to wfMessage()
524 * @param key string Key of message to get
525 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
528 this.message = function( key
, parameters
) {
529 // Support variadic arguments
530 if ( typeof parameters
!== 'undefined' ) {
531 parameters
= $.makeArray( arguments
);
536 return new Message( mw
.messages
, key
, parameters
);
540 * Gets a message string, similar to wfMsg()
542 * @param key string Key of message to get
543 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
546 this.msg = function( key
, parameters
) {
547 return mw
.message
.apply( mw
.message
, arguments
).toString();
551 * Client-side module loader which integrates with the MediaWiki ResourceLoader
553 this.loader
= new ( function() {
555 /* Private Members */
558 * Mapping of registered modules
560 * The jquery module is pre-registered, because it must have already
561 * been provided for this object to have been built, and in debug mode
562 * jquery would have been provided through a unique loader request,
563 * making it impossible to hold back registration of jquery until after
569 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
570 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
571 * 'script': function() {},
572 * 'style': 'css code string',
573 * 'messages': { 'key': 'value' },
574 * 'version': ############## (unix timestamp)
579 // List of modules which will be loaded as when ready
581 // List of modules to be loaded
583 // List of callback functions waiting for modules to be ready to be called
585 // Flag inidicating that document ready has occured
587 // Selector cache for the marker element. Use getMarker() to get/use the marker!
590 /* Private Methods */
592 function getMarker(){
597 //mw.log( 'getMarker> Caching marker' );
598 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
599 if ( $marker
.length
) {
602 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
603 return $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
607 function compare( a
, b
) {
608 if ( a
.length
!= b
.length
) {
611 for ( var i
= 0; i
< b
.length
; i
++ ) {
612 if ( $.isArray( a
[i
] ) ) {
613 if ( !compare( a
[i
], b
[i
] ) ) {
617 if ( a
[i
] !== b
[i
] ) {
625 * Generates an ISO8601 "basic" string from a UNIX timestamp
627 function formatVersionNumber( timestamp
) {
628 function pad( a
, b
, c
) {
629 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
632 d
.setTime( timestamp
* 1000 );
634 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
635 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
640 * Recursively resolves dependencies and detects circular references
642 function recurse( module
, resolved
, unresolved
) {
643 if ( typeof registry
[module
] === 'undefined' ) {
644 throw new Error( 'Unknown dependency: ' + module
);
646 // Resolves dynamic loader function and replaces it with its own results
647 if ( $.isFunction( registry
[module
].dependencies
) ) {
648 registry
[module
].dependencies
= registry
[module
].dependencies();
649 // Ensures the module's dependencies are always in an array
650 if ( typeof registry
[module
].dependencies
!== 'object' ) {
651 registry
[module
].dependencies
= [registry
[module
].dependencies
];
654 // Tracks down dependencies
655 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
656 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
657 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
659 'Circular reference detected: ' + module
+
660 ' -> ' + registry
[module
].dependencies
[n
]
663 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
666 resolved
[resolved
.length
] = module
;
667 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
671 * Gets a list of module names that a module depends on in their proper dependency order
673 * @param module string module name or array of string module names
674 * @return list of dependencies
675 * @throws Error if circular reference is detected
677 function resolve( module
) {
678 // Allow calling with an array of module names
679 if ( typeof module
=== 'object' ) {
681 for ( var m
= 0; m
< module
.length
; m
++ ) {
682 var dependencies
= resolve( module
[m
] );
683 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
684 modules
[modules
.length
] = dependencies
[n
];
688 } else if ( typeof module
=== 'string' ) {
689 // Undefined modules have no dependencies
690 if ( !( module
in registry
) ) {
694 recurse( module
, resolved
, [] );
697 throw new Error( 'Invalid module argument: ' + module
);
701 * Narrows a list of module names down to those matching a specific
702 * state. Possible states are 'undefined', 'registered', 'loading',
703 * 'loaded', or 'ready'
705 * @param states string or array of strings of module states to filter by
706 * @param modules array list of module names to filter (optional, all modules
707 * will be used by default)
708 * @return array list of filtered module names
710 function filter( states
, modules
) {
711 // Allow states to be given as a string
712 if ( typeof states
=== 'string' ) {
715 // If called without a list of modules, build and use a list of all modules
716 var list
= [], module
;
717 if ( typeof modules
=== 'undefined' ) {
719 for ( module
in registry
) {
720 modules
[modules
.length
] = module
;
723 // Build a list of modules which are in one of the specified states
724 for ( var s
= 0; s
< states
.length
; s
++ ) {
725 for ( var m
= 0; m
< modules
.length
; m
++ ) {
726 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
727 // Module does not exist
728 if ( states
[s
] == 'undefined' ) {
730 list
[list
.length
] = modules
[m
];
733 // Module exists, check state
734 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
736 list
[list
.length
] = modules
[m
];
745 * Executes a loaded module, making it ready to use
747 * @param module string module name to execute
749 function execute( module
, callback
) {
750 var _fn
= 'mw.loader::execute> ';
751 if ( typeof registry
[module
] === 'undefined' ) {
752 throw new Error( 'Module has not been registered yet: ' + module
);
753 } else if ( registry
[module
].state
=== 'registered' ) {
754 throw new Error( 'Module has not been requested from the server yet: ' + module
);
755 } else if ( registry
[module
].state
=== 'loading' ) {
756 throw new Error( 'Module has not completed loading yet: ' + module
);
757 } else if ( registry
[module
].state
=== 'ready' ) {
758 throw new Error( 'Module has already been loaded: ' + module
);
761 if ( $.isPlainObject( registry
[module
].style
) ) {
762 for ( var media
in registry
[module
].style
) {
763 var style
= registry
[module
].style
[media
];
764 if ( $.isArray( style
) ) {
765 for ( var i
= 0; i
< style
.length
; i
++ ) {
766 getMarker().before( mw
.html
.element( 'link', {
772 } else if ( typeof style
=== 'string' ) {
773 getMarker().before( mw
.html
.element(
775 { 'type': 'text/css', 'media': media
},
776 new mw
.html
.Cdata( style
)
781 // Add localizations to message system
782 if ( $.isPlainObject( registry
[module
].messages
) ) {
783 mw
.messages
.set( registry
[module
].messages
);
787 var script
= registry
[module
].script
;
788 if ( $.isArray( script
) ) {
790 for ( var i
= 0; i
< script
.length
; i
++ ) {
791 registry
[module
].state
= 'loading';
792 addScript( script
[i
], function() {
793 if ( ++done
== script
.length
) {
794 registry
[module
].state
= 'ready';
796 if ( $.isFunction( callback
) ) {
802 } else if ( $.isFunction( script
) ) {
804 registry
[module
].state
= 'ready';
806 if ( $.isFunction( callback
) ) {
811 // This needs to NOT use mw.log because these errors are common in production mode
812 // and not in debug mode, such as when a symbol that should be global isn't exported
813 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
814 console
.log( _fn
+ 'Exception thrown by ' + module
+ ': ' + e
.message
);
817 registry
[module
].state
= 'error';
822 * Automatically executes jobs and modules which are pending with satistifed dependencies.
824 * This is used when dependencies are satisfied, such as when a module is executed.
826 function handlePending() {
828 // Run jobs who's dependencies have just been met
829 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
831 filter( 'ready', jobs
[j
].dependencies
),
832 jobs
[j
].dependencies
) )
834 if ( $.isFunction( jobs
[j
].ready
) ) {
841 // Execute modules who's dependencies have just been met
842 for ( var r
in registry
) {
843 if ( registry
[r
].state
== 'loaded' ) {
845 filter( ['ready'], registry
[r
].dependencies
),
846 registry
[r
].dependencies
) )
853 // Run error callbacks of jobs affected by this condition
854 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
855 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
856 if ( $.isFunction( jobs
[j
].error
) ) {
867 * Adds a dependencies to the queue with optional callbacks to be run
868 * when the dependencies are ready or fail
870 * @param dependencies string module name or array of string module names
871 * @param ready function callback to execute when all dependencies are ready
872 * @param error function callback to execute when any dependency fails
874 function request( dependencies
, ready
, error
) {
875 // Allow calling by single module name
876 if ( typeof dependencies
=== 'string' ) {
877 dependencies
= [dependencies
];
878 if ( dependencies
[0] in registry
) {
879 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
880 dependencies
[dependencies
.length
] =
881 registry
[dependencies
[0]].dependencies
[n
];
885 // Add ready and error callbacks if they were given
886 if ( arguments
.length
> 1 ) {
887 jobs
[jobs
.length
] = {
888 'dependencies': filter(
889 ['undefined', 'registered', 'loading', 'loaded'],
895 // Queue up any dependencies that are undefined or registered
896 dependencies
= filter( ['undefined', 'registered'], dependencies
);
897 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
898 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
899 queue
[queue
.length
] = dependencies
[n
];
906 function sortQuery(o
) {
907 var sorted
= {}, key
, a
= [];
909 if ( o
.hasOwnProperty( key
) ) {
914 for ( key
= 0; key
< a
.length
; key
++ ) {
915 sorted
[a
[key
]] = o
[a
[key
]];
921 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
922 * to a query string of the form foo.bar,baz|bar.baz,quux
924 function buildModulesString( moduleMap
) {
926 for ( var prefix
in moduleMap
) {
927 var p
= prefix
=== '' ? '' : prefix
+ '.';
928 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
930 return arr
.join( '|' ).replace( /\./g, '!' );
934 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
935 * depending on whether document-ready has occured yet.
937 * @param src String: URL to script, will be used as the src attribute in the script tag
938 * @param callback Function: Optional callback which will be run when the script is done
940 function addScript( src
, callback
) {
942 // jQuery's getScript method is NOT better than doing this the old-fassioned way
943 // because jQuery will eval the script's code, and errors will not have sane
945 var script
= document
.createElement( 'script' );
946 script
.setAttribute( 'src', src
);
947 script
.setAttribute( 'type', 'text/javascript' );
948 if ( $.isFunction( callback
) ) {
950 // Attach handlers for all browsers -- this is based on jQuery.getScript
951 script
.onload
= script
.onreadystatechange = function() {
956 || this.readyState
=== "loaded"
957 || this.readyState
=== "complete"
962 // Handle memory leak in IE
963 script
.onload
= script
.onreadystatechange
= null;
964 if ( script
.parentNode
) {
965 script
.parentNode
.removeChild( script
);
970 document
.body
.appendChild( script
);
972 document
.write( mw
.html
.element(
973 'script', { 'type': 'text/javascript', 'src': src
}, ''
975 if ( $.isFunction( callback
) ) {
976 // Document.write is synchronous, so this is called when it's done
985 * Requests dependencies from server, loading and executing when things when ready.
987 this.work = function() {
988 // Appends a list of modules to the batch
989 for ( var q
= 0; q
< queue
.length
; q
++ ) {
990 // Only request modules which are undefined or registered
991 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
992 // Prevent duplicate entries
993 if ( $.inArray( queue
[q
], batch
) === -1 ) {
994 batch
[batch
.length
] = queue
[q
];
995 // Mark registered modules as loading
996 if ( queue
[q
] in registry
) {
997 registry
[queue
[q
]].state
= 'loading';
1002 // Early exit if there's nothing to load
1003 if ( !batch
.length
) {
1006 // Clean up the queue
1008 // Always order modules alphabetically to help reduce cache
1009 // misses for otherwise identical content
1011 // Build a list of request parameters
1013 'skin': mw
.config
.get( 'skin' ),
1014 'lang': mw
.config
.get( 'wgUserLanguage' ),
1015 'debug': mw
.config
.get( 'debug' )
1017 // Extend request parameters with a list of modules in the batch
1019 // Split into groups
1021 for ( var b
= 0; b
< batch
.length
; b
++ ) {
1022 var group
= registry
[batch
[b
]].group
;
1023 if ( !( group
in groups
) ) {
1026 groups
[group
][groups
[group
].length
] = batch
[b
];
1028 for ( var group
in groups
) {
1029 // Calculate the highest timestamp
1031 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
1032 if ( registry
[groups
[group
][g
]].version
> version
) {
1033 version
= registry
[groups
[group
][g
]].version
;
1036 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
);
1037 var reqBaseLength
= $.param( reqBase
).length
;
1039 var limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1040 // We may need to split up the request to honor the query string length limit
1041 // So build it piece by piece
1042 var l
= reqBaseLength
+ 9; // '&modules='.length == 9
1044 reqs
[0] = {}; // { prefix: [ suffixes ] }
1045 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
1046 // Determine how many bytes this module would add to the query string
1047 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' );
1048 // Note that these substr() calls work even if lastDotIndex == -1
1049 var prefix
= groups
[group
][i
].substr( 0, lastDotIndex
);
1050 var suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 );
1051 var bytesAdded
= prefix
in reqs
[r
] ?
1052 suffix
.length
+ 3 : // '%2C'.length == 3
1053 groups
[group
][i
].length
+ 3; // '%7C'.length == 3
1055 // If the request would become too long, create a new one,
1056 // but don't create empty requests
1057 if ( limit
> 0 && reqs
[r
] != {} && l
+ bytesAdded
> limit
) {
1058 // This request would become too long, create a new one
1061 l
= reqBaseLength
+ 9;
1063 if ( !( prefix
in reqs
[r
] ) ) {
1064 reqs
[r
][prefix
] = [];
1066 reqs
[r
][prefix
].push( suffix
);
1069 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
1070 requests
[requests
.length
] = $.extend(
1071 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
1075 // Clear the batch - this MUST happen before we append the
1076 // script element to the body or it's possible that the script
1077 // will be locally cached, instantly load, and work the batch
1078 // again, all before we've cleared it causing each request to
1079 // include modules which are already loaded
1081 // Asynchronously append a script tag to the end of the body
1082 for ( var r
= 0; r
< requests
.length
; r
++ ) {
1083 requests
[r
] = sortQuery( requests
[r
] );
1084 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
1090 * Registers a module, letting the system know about it and its
1091 * dependencies. loader.js files contain calls to this function.
1093 this.register = function( module
, version
, dependencies
, group
) {
1094 // Allow multiple registration
1095 if ( typeof module
=== 'object' ) {
1096 for ( var m
= 0; m
< module
.length
; m
++ ) {
1097 if ( typeof module
[m
] === 'string' ) {
1098 mw
.loader
.register( module
[m
] );
1099 } else if ( typeof module
[m
] === 'object' ) {
1100 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1106 if ( typeof module
!== 'string' ) {
1107 throw new Error( 'module must be a string, not a ' + typeof module
);
1109 if ( typeof registry
[module
] !== 'undefined' ) {
1110 throw new Error( 'module already implemented: ' + module
);
1112 // List the module as registered
1113 registry
[module
] = {
1114 'state': 'registered',
1115 'group': typeof group
=== 'string' ? group
: null,
1117 'version': typeof version
!== 'undefined' ? parseInt( version
, 10 ) : 0
1119 if ( typeof dependencies
=== 'string' ) {
1120 // Allow dependencies to be given as a single module name
1121 registry
[module
].dependencies
= [dependencies
];
1122 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1123 // Allow dependencies to be given as an array of module names
1124 // or a function which returns an array
1125 registry
[module
].dependencies
= dependencies
;
1130 * Implements a module, giving the system a course of action to take
1131 * upon loading. Results of a request for one or more modules contain
1132 * calls to this function.
1134 * All arguments are required.
1136 * @param module String: Name of module
1137 * @param script Mixed: Function of module code or String of URL to be used as the src
1138 * attribute when adding a script element to the body
1139 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1140 * keyed by media-type
1141 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1143 this.implement = function( module
, script
, style
, msgs
) {
1145 if ( typeof module
!== 'string' ) {
1146 throw new Error( 'module must be a string, not a ' + typeof module
);
1148 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1149 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1151 if ( !$.isPlainObject( style
) ) {
1152 throw new Error( 'style must be an object, not a ' + typeof style
);
1154 if ( !$.isPlainObject( msgs
) ) {
1155 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1157 // Automatically register module
1158 if ( typeof registry
[module
] === 'undefined' ) {
1159 mw
.loader
.register( module
);
1161 // Check for duplicate implementation
1162 if ( typeof registry
[module
] !== 'undefined'
1163 && typeof registry
[module
].script
!== 'undefined' )
1165 throw new Error( 'module already implemeneted: ' + module
);
1167 // Mark module as loaded
1168 registry
[module
].state
= 'loaded';
1169 // Attach components
1170 registry
[module
].script
= script
;
1171 registry
[module
].style
= style
;
1172 registry
[module
].messages
= msgs
;
1173 // Execute or queue callback
1175 filter( ['ready'], registry
[module
].dependencies
),
1176 registry
[module
].dependencies
) )
1185 * Executes a function as soon as one or more required modules are ready
1187 * @param dependencies string or array of strings of modules names the callback
1188 * dependencies to be ready before
1190 * @param ready function callback to execute when all dependencies are ready (optional)
1191 * @param error function callback to execute when if dependencies have a errors (optional)
1193 this.using = function( dependencies
, ready
, error
) {
1195 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
1196 throw new Error( 'dependencies must be a string or an array, not a ' +
1197 typeof dependencies
);
1199 // Allow calling with a single dependency as a string
1200 if ( typeof dependencies
=== 'string' ) {
1201 dependencies
= [dependencies
];
1203 // Resolve entire dependency map
1204 dependencies
= resolve( dependencies
);
1205 // If all dependencies are met, execute ready immediately
1206 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1207 if ( $.isFunction( ready
) ) {
1211 // If any dependencies have errors execute error immediately
1212 else if ( filter( ['error'], dependencies
).length
) {
1213 if ( $.isFunction( error
) ) {
1217 // Since some dependencies are not yet ready, queue up a request
1219 request( dependencies
, ready
, error
);
1224 * Loads an external script or one or more modules for future use
1226 * @param modules mixed either the name of a module, array of modules,
1227 * or a URL of an external script or style
1228 * @param type string mime-type to use if calling with a URL of an
1229 * external script or style; acceptable values are "text/css" and
1230 * "text/javascript"; if no type is provided, text/javascript is
1233 this.load = function( modules
, type
) {
1235 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1236 throw new Error( 'modules must be a string or an array, not a ' +
1239 // Allow calling with an external script or single dependency as a string
1240 if ( typeof modules
=== 'string' ) {
1241 // Support adding arbitrary external scripts
1242 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
1243 if ( type
=== 'text/css' ) {
1244 $( 'head' ).append( $( '<link />', {
1250 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
1251 addScript( modules
);
1257 // Called with single module
1258 modules
= [modules
];
1260 // Resolve entire dependency map
1261 modules
= resolve( modules
);
1262 // If all modules are ready, nothing dependency be done
1263 if ( compare( filter( ['ready'], modules
), modules
) ) {
1266 // If any modules have errors return false
1267 else if ( filter( ['error'], modules
).length
) {
1270 // Since some modules are not yet ready, queue up a request
1278 * Changes the state of a module
1280 * @param module string module name or object of module name/state pairs
1281 * @param state string state name
1283 this.state = function( module
, state
) {
1284 if ( typeof module
=== 'object' ) {
1285 for ( var m
in module
) {
1286 mw
.loader
.state( m
, module
[m
] );
1290 if ( !( module
in registry
) ) {
1291 mw
.loader
.register( module
);
1293 registry
[module
].state
= state
;
1297 * Gets the version of a module
1299 * @param module string name of module to get version for
1301 this.getVersion = function( module
) {
1302 if ( module
in registry
&& 'version' in registry
[module
] ) {
1303 return formatVersionNumber( registry
[module
].version
);
1308 * @deprecated use mw.loader.getVersion() instead
1310 this.version = function() {
1311 return mediaWiki
.loader
.getVersion
.apply( mediaWiki
.loader
, arguments
);
1315 * Gets the state of a module
1317 * @param module string name of module to get state for
1319 this.getState = function( module
) {
1320 if ( module
in registry
&& 'state' in registry
[module
] ) {
1321 return registry
[module
].state
;
1326 /* Cache document ready status */
1328 $(document
).ready( function() { ready
= true; } );
1331 /** HTML construction helper functions */
1332 this.html
= new ( function () {
1333 var escapeCallback = function( s
) {
1349 * Escape a string for HTML. Converts special characters to HTML entities.
1350 * @param s The string to escape
1352 this.escape = function( s
) {
1353 return s
.replace( /['"<>&]/g, escapeCallback
);
1357 * Wrapper object for raw HTML passed to mw.html.element().
1359 this.Raw = function( value
) {
1364 * Wrapper object for CDATA element contents passed to mw.html.element()
1366 this.Cdata = function( value
) {
1371 * Create an HTML element string, with safe escaping.
1373 * @param name The tag name.
1374 * @param attrs An object with members mapping element names to values
1375 * @param contents The contents of the element. May be either:
1376 * - string: The string is escaped.
1377 * - null or undefined: The short closing form is used, e.g. <br/>.
1378 * - this.Raw: The value attribute is included without escaping.
1379 * - this.Cdata: The value attribute is included, and an exception is
1380 * thrown if it contains an illegal ETAGO delimiter.
1381 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1385 * return h.element( 'div', {},
1386 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1387 * Returns <div><img src="<"/></div>
1389 this.element = function( name
, attrs
, contents
) {
1391 for ( var attrName
in attrs
) {
1392 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1394 if ( typeof contents
== 'undefined' || contents
=== null ) {
1401 if ( typeof contents
=== 'string') {
1403 s
+= this.escape( contents
);
1404 } else if ( contents
instanceof this.Raw
) {
1405 // Raw HTML inclusion
1406 s
+= contents
.value
;
1407 } else if ( contents
instanceof this.Cdata
) {
1409 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1410 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1412 s
+= contents
.value
;
1414 throw new Error( 'mw.html.element: Invalid type of contents' );
1416 s
+= '</' + name
+ '>';
1421 /* Extension points */
1427 // Alias $j to jQuery for backwards compatibility
1429 window
.mw
= mediaWiki
;
1431 /* Auto-register from pre-loaded startup scripts */
1433 if ( $.isFunction( startUp
) ) {
1438 // Add jQuery Cookie to initial payload (used in mw.user)
1439 mw
.loader
.load( 'jquery.cookie' );