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
) {
68 // Iterate over each property
69 for ( var prop
in objectA
) {
70 // Check if this property is also present in the other object
71 if ( prop
in objectB
) {
72 // Compare the types of the properties
73 var type
= typeof( objectA
[prop
] );
74 if ( type
== typeof( objectB
[prop
] ) ) {
75 // Recursively check objects inside this one
78 if ( !$.compareObject( objectA
[prop
], objectB
[prop
] ) ) {
83 // Functions need to be strings to compare them properly
84 if ( objectA
[prop
].toString() !== objectB
[prop
].toString() ) {
90 if ( objectA
[prop
] !== objectB
[prop
] ) {
102 // Check for properties in B but not in A
103 // This is about 15% faster (tested in Safari 5 and Firefox 3.6)
104 // ...than incrementing a count variable in the above and below loops
105 // See also: http://www.mediawiki.org/wiki/ResourceLoader/Default_modules/compareObject_test#Results
106 for ( var prop
in objectB
) {
107 if ( !( prop
in objectA
) ) {
121 * Core MediaWiki JavaScript Library
125 window
.mediaWiki
= new ( function( $ ) {
129 // This will not change until we are 100% ready to turn off legacy globals
130 var LEGACY_GLOBALS
= true;
132 /* Private Members */
134 // List of messages that have been requested to be loaded
135 var messageQueue
= {};
140 * An object which allows single and multiple get/set/exists functionality
141 * on a list of key / value pairs.
143 * @param {boolean} global Whether to get/set/exists values on the window
144 * object or a private object
146 function Map( global
) {
147 this.values
= ( global
=== true ) ? window
: {};
151 * Gets the value of a key, or a list of key/value pairs for an array of keys.
153 * If called with no arguments, all values will be returned.
155 * @param selection mixed Key or array of keys to get values for
156 * @param fallback mixed Value to use in case key(s) do not exist (optional)
158 Map
.prototype.get = function( selection
, fallback
) {
159 if ( typeof selection
=== 'object' ) {
160 selection
= $.makeArray( selection
);
162 for ( var i
= 0; i
< selection
.length
; i
++ ) {
163 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
166 } else if ( typeof selection
=== 'string' ) {
167 if ( typeof this.values
[selection
] === 'undefined' ) {
168 if ( typeof fallback
!== 'undefined' ) {
173 return this.values
[selection
];
179 * Sets one or multiple key/value pairs.
181 * @param selection mixed Key or object of key/value pairs to set
182 * @param value mixed Value to set (optional, only in use when key is a string)
184 Map
.prototype.set = function( selection
, value
) {
185 if ( typeof selection
=== 'object' ) {
186 for ( var s
in selection
) {
187 this.values
[s
] = selection
[s
];
189 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
190 this.values
[selection
] = value
;
195 * Checks if one or multiple keys exist.
197 * @param selection mixed Key or array of keys to check
198 * @return boolean Existence of key(s)
200 Map
.prototype.exists = function( selection
) {
201 if ( typeof selection
=== 'object' ) {
202 for ( var s
= 0; s
< selection
.length
; s
++ ) {
203 if ( !( selection
[s
] in this.values
) ) {
209 return selection
in this.values
;
214 * Message object, similar to Message in PHP
216 function Message( map
, key
, parameters
) {
217 this.format
= 'parse';
220 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
224 * Appends parameters for replacement
226 * @param parameters mixed First in a list of variadic arguments to append as message parameters
228 Message
.prototype.params = function( parameters
) {
229 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
230 this.parameters
[this.parameters
.length
] = parameters
[i
];
236 * Converts message object to it's string form based on the state of format
238 * @return {string} String form of message
240 Message
.prototype.toString = function() {
241 if ( !this.map
.exists( this.key
) ) {
242 // Return <key> if key does not exist
243 return '<' + this.key
+ '>';
245 var text
= this.map
.get( this.key
);
246 var parameters
= this.parameters
;
247 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
248 var index
= parseInt( match
, 10 ) - 1;
249 return index
in parameters
? parameters
[index
] : '$' + match
;
252 if ( this.format
=== 'plain' ) {
255 if ( this.format
=== 'escaped' ) {
256 // According to Message.php this needs {{-transformation, which is
258 return mediaWiki
.html
.escape( text
);
261 /* This should be fixed up when we have a parser
262 if ( this.format === 'parse' && 'language' in mediaWiki ) {
263 text = mediaWiki.language.parse( text );
270 * Changes format to parse and converts message to string
272 * @return {string} String form of parsed message
274 Message
.prototype.parse = function() {
275 this.format
= 'parse';
276 return this.toString();
280 * Changes format to plain and converts message to string
282 * @return {string} String form of plain message
284 Message
.prototype.plain = function() {
285 this.format
= 'plain';
286 return this.toString();
290 * Changes the format to html escaped and converts message to string
292 * @return {string} String form of html escaped message
294 Message
.prototype.escaped = function() {
295 this.format
= 'escaped';
296 return this.toString();
300 * Checks if message exists
302 * @return {string} String form of parsed message
304 Message
.prototype.exists = function() {
305 return this.map
.exists( this.key
);
313 /* Private Members */
319 this.options
= new Map();
324 * Generates a random user session ID (32 alpha-numeric characters).
326 * This information would potentially be stored in a cookie to identify a user during a
327 * session or series of sessions. It's uniqueness should not be depended on.
329 * @return string random set of 32 alpha-numeric characters
331 function generateId() {
333 var seed
= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
334 for ( var i
= 0, r
; i
< 32; i
++ ) {
335 r
= Math
.floor( Math
.random() * seed
.length
);
336 id
+= seed
.substring( r
, r
+ 1 );
342 * Gets the current user's name.
344 * @return mixed user name string or null if users is anonymous
346 this.name = function() {
347 return mediaWiki
.config
.get( 'wgUserName' );
351 * Checks if the current user is anonymous.
355 this.anonymous = function() {
356 return that
.name() ? false : true;
360 * Gets a random session ID automatically generated and kept in a cookie.
362 * This ID is ephemeral for everyone, staying in their browser only until they close
365 * Do not use this method before the first call to mw.loader.go(), it depends on
366 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
367 * won't be loaded until the first call to go().
369 * @return string user name or random session ID
371 this.sessionId = function () {
372 var sessionId
= $.cookie( 'mediaWiki.user.sessionId' );
373 if ( typeof sessionId
== 'undefined' || sessionId
=== null ) {
374 sessionId
= generateId();
375 $.cookie( 'mediaWiki.user.sessionId', sessionId
, { 'expires': null, 'path': '/' } );
381 * Gets the current user's name or a random ID automatically generated and kept in a cookie.
383 * This ID is persistent for anonymous users, staying in their browser up to 1 year. The
384 * expiration time is reset each time the ID is queried, so in most cases this ID will
385 * persist until the browser's cookies are cleared or the user doesn't visit for 1 year.
387 * Do not use this method before the first call to mw.loader.go(), it depends on
388 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
389 * won't be loaded until the first call to go().
391 * @return string user name or random session ID
393 this.id = function() {
394 var name
= that
.name();
398 var id
= $.cookie( 'mediaWiki.user.id' );
399 if ( typeof id
== 'undefined' || id
=== null ) {
402 // Set cookie if not set, or renew it if already set
403 $.cookie( 'mediaWiki.user.id', id
, { 'expires': 365, 'path': '/' } );
408 * Gets the user's bucket, placing them in one at random based on set odds if needed.
410 * @param key String: Name of bucket
411 * @param options Object: Bucket configuration options
412 * @param options.buckets Object: List of bucket-name/relative-probability pairs (required,
413 * must have at least one pair)
414 * @param options.version Number: Version of bucket test, changing this forces rebucketing
415 * (optional, default: 0)
416 * @param options.tracked Boolean: Track the event of bucketing through the API module of
417 * the ClickTracking extension (optional, default: false)
418 * @param options.expires Number: Length of time (in days) until the user gets rebucketed
419 * (optional, default: 30)
420 * @return String: Bucket name - the randomly chosen key of the options.buckets object
423 * mw.user.bucket( 'test', {
424 * 'buckets': { 'ignored': 50, 'control': 25, 'test': 25 },
430 this.bucket = function( key
, options
) {
431 options
= $.extend( {
437 var cookie
= $.cookie( 'mediaWiki.user.bucket:' + key
);
440 // Bucket information is stored as 2 integers, together as version:bucket like: "1:2"
441 if ( typeof cookie
=== 'string' && cookie
.length
> 2 && cookie
.indexOf( ':' ) > 0 ) {
442 var parts
= cookie
.split( ':' );
443 if ( parts
.length
> 1 && parts
[0] == options
.version
) {
444 version
= Number( parts
[0] );
445 bucket
= String( parts
[1] );
448 if ( bucket
=== null ) {
449 if ( !$.isPlainObject( options
.buckets
) ) {
450 throw 'Invalid buckets error. Object expected for options.buckets.';
452 version
= Number( options
.version
);
455 for ( var k
in options
.buckets
) {
456 range
+= options
.buckets
[k
];
458 // Select random value within range
459 var rand
= Math
.random() * range
;
460 // Determine which bucket the value landed in
462 for ( var k
in options
.buckets
) {
464 total
+= options
.buckets
[k
];
465 if ( total
>= rand
) {
469 if ( options
.tracked
) {
470 mw
.loader
.using( 'jquery.clickTracking', function() {
472 'mediaWiki.user.bucket:' + key
+ '@' + version
+ ':' + bucket
477 'mediaWiki.user.bucket:' + key
,
478 version
+ ':' + bucket
,
479 { 'path': '/', 'expires': Number( options
.expires
) }
489 * Dummy function which in debug mode can be replaced with a function that
490 * does something clever
492 this.log = function() { };
495 * Make the Map-class publicly available
500 * List of configuration values
502 * In legacy mode the values this object wraps will be in the global space
504 this.config
= new this.Map( LEGACY_GLOBALS
);
507 * Information about the current user
509 this.user
= new User();
512 * Localization system
514 this.messages
= new this.Map();
519 * Gets a message object, similar to wfMessage()
521 * @param key string Key of message to get
522 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
525 this.message = function( key
, parameters
) {
526 // Support variadic arguments
527 if ( typeof parameters
!== 'undefined' ) {
528 parameters
= $.makeArray( arguments
);
533 return new Message( mediaWiki
.messages
, key
, parameters
);
537 * Gets a message string, similar to wfMsg()
539 * @param key string Key of message to get
540 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
543 this.msg = function( key
, parameters
) {
544 return mediaWiki
.message
.apply( mediaWiki
.message
, arguments
).toString();
548 * Client-side module loader which integrates with the MediaWiki ResourceLoader
550 this.loader
= new ( function() {
552 /* Private Members */
555 * Mapping of registered modules
557 * The jquery module is pre-registered, because it must have already
558 * been provided for this object to have been built, and in debug mode
559 * jquery would have been provided through a unique loader request,
560 * making it impossible to hold back registration of jquery until after
566 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
567 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
568 * 'script': function() {},
569 * 'style': 'css code string',
570 * 'messages': { 'key': 'value' },
571 * 'version': ############## (unix timestamp)
576 // List of modules which will be loaded as when ready
578 // List of modules to be loaded
580 // List of callback functions waiting for modules to be ready to be called
582 // Flag indicating that requests should be suspended
583 var suspended
= true;
584 // Flag inidicating that document ready has occured
586 // Marker element for adding dynamic styles
587 var $marker
= $( 'head meta[name=ResourceLoaderDynamicStyles]' );
589 /* Private Methods */
591 function compare( a
, b
) {
592 if ( a
.length
!= b
.length
) {
595 for ( var i
= 0; i
< b
.length
; i
++ ) {
596 if ( $.isArray( a
[i
] ) ) {
597 if ( !compare( a
[i
], b
[i
] ) ) {
601 if ( a
[i
] !== b
[i
] ) {
609 * Generates an ISO8601 "basic" string from a UNIX timestamp
611 function formatVersionNumber( timestamp
) {
612 function pad( a
, b
, c
) {
613 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
616 d
.setTime( timestamp
* 1000 );
618 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
619 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
624 * Recursively resolves dependencies and detects circular references
626 function recurse( module
, resolved
, unresolved
) {
627 if ( typeof registry
[module
] === 'undefined' ) {
628 throw new Error( 'Unknown dependency: ' + module
);
630 // Resolves dynamic loader function and replaces it with its own results
631 if ( $.isFunction( registry
[module
].dependencies
) ) {
632 registry
[module
].dependencies
= registry
[module
].dependencies();
633 // Ensures the module's dependencies are always in an array
634 if ( typeof registry
[module
].dependencies
!== 'object' ) {
635 registry
[module
].dependencies
= [registry
[module
].dependencies
];
638 // Tracks down dependencies
639 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
640 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
641 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
643 'Circular reference detected: ' + module
+
644 ' -> ' + registry
[module
].dependencies
[n
]
647 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
650 resolved
[resolved
.length
] = module
;
651 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
655 * Gets a list of module names that a module depends on in their proper dependency order
657 * @param module string module name or array of string module names
658 * @return list of dependencies
659 * @throws Error if circular reference is detected
661 function resolve( module
) {
662 // Allow calling with an array of module names
663 if ( typeof module
=== 'object' ) {
665 for ( var m
= 0; m
< module
.length
; m
++ ) {
666 var dependencies
= resolve( module
[m
] );
667 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
668 modules
[modules
.length
] = dependencies
[n
];
672 } else if ( typeof module
=== 'string' ) {
673 // Undefined modules have no dependencies
674 if ( !( module
in registry
) ) {
678 recurse( module
, resolved
, [] );
681 throw new Error( 'Invalid module argument: ' + module
);
685 * Narrows a list of module names down to those matching a specific
686 * state. Possible states are 'undefined', 'registered', 'loading',
687 * 'loaded', or 'ready'
689 * @param states string or array of strings of module states to filter by
690 * @param modules array list of module names to filter (optional, all modules
691 * will be used by default)
692 * @return array list of filtered module names
694 function filter( states
, modules
) {
695 // Allow states to be given as a string
696 if ( typeof states
=== 'string' ) {
699 // If called without a list of modules, build and use a list of all modules
700 var list
= [], module
;
701 if ( typeof modules
=== 'undefined' ) {
703 for ( module
in registry
) {
704 modules
[modules
.length
] = module
;
707 // Build a list of modules which are in one of the specified states
708 for ( var s
= 0; s
< states
.length
; s
++ ) {
709 for ( var m
= 0; m
< modules
.length
; m
++ ) {
710 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
711 // Module does not exist
712 if ( states
[s
] == 'undefined' ) {
714 list
[list
.length
] = modules
[m
];
717 // Module exists, check state
718 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
720 list
[list
.length
] = modules
[m
];
729 * Executes a loaded module, making it ready to use
731 * @param module string module name to execute
733 function execute( module
) {
734 var _fn
= 'mw.loader::execute> ';
735 if ( typeof registry
[module
] === 'undefined' ) {
736 throw new Error( 'Module has not been registered yet: ' + module
);
737 } else if ( registry
[module
].state
=== 'registered' ) {
738 throw new Error( 'Module has not been requested from the server yet: ' + module
);
739 } else if ( registry
[module
].state
=== 'loading' ) {
740 throw new Error( 'Module has not completed loading yet: ' + module
);
741 } else if ( registry
[module
].state
=== 'ready' ) {
742 throw new Error( 'Module has already been loaded: ' + module
);
744 // Add style sheet to document
745 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
746 $marker
.before( mediaWiki
.html
.element( 'style',
747 { type
: 'text/css' },
748 new mediaWiki
.html
.Cdata( registry
[module
].style
)
750 } else if ( typeof registry
[module
].style
=== 'object'
751 && !( $.isArray( registry
[module
].style
) ) )
753 for ( var media
in registry
[module
].style
) {
754 $marker
.before( mediaWiki
.html
.element( 'style',
755 { type
: 'text/css', media
: media
},
756 new mediaWiki
.html
.Cdata( registry
[module
].style
[media
] )
760 // Add localizations to message system
761 if ( typeof registry
[module
].messages
=== 'object' ) {
762 mediaWiki
.messages
.set( registry
[module
].messages
);
766 registry
[module
].script( jQuery
);
767 registry
[module
].state
= 'ready';
768 // Run jobs who's dependencies have just been met
769 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
771 filter( 'ready', jobs
[j
].dependencies
),
772 jobs
[j
].dependencies
) )
774 if ( $.isFunction( jobs
[j
].ready
) ) {
781 // Execute modules who's dependencies have just been met
782 for ( var r
in registry
) {
783 if ( registry
[r
].state
== 'loaded' ) {
785 filter( ['ready'], registry
[r
].dependencies
),
786 registry
[r
].dependencies
) )
793 // This needs to NOT use mw.log because these errors are common in production mode
794 // and not in debug mode, such as when a symbol that should be global isn't exported
795 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
796 console
.log( _fn
+ 'Exception thrown by ' + module
+ ': ' + e
.message
);
799 registry
[module
].state
= 'error';
800 // Run error callbacks of jobs affected by this condition
801 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
802 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
803 if ( $.isFunction( jobs
[j
].error
) ) {
814 * Adds a dependencies to the queue with optional callbacks to be run
815 * when the dependencies are ready or fail
817 * @param dependencies string module name or array of string module names
818 * @param ready function callback to execute when all dependencies are ready
819 * @param error function callback to execute when any dependency fails
821 function request( dependencies
, ready
, error
) {
822 // Allow calling by single module name
823 if ( typeof dependencies
=== 'string' ) {
824 dependencies
= [dependencies
];
825 if ( dependencies
[0] in registry
) {
826 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
827 dependencies
[dependencies
.length
] =
828 registry
[dependencies
[0]].dependencies
[n
];
832 // Add ready and error callbacks if they were given
833 if ( arguments
.length
> 1 ) {
834 jobs
[jobs
.length
] = {
835 'dependencies': filter(
836 ['undefined', 'registered', 'loading', 'loaded'],
842 // Queue up any dependencies that are undefined or registered
843 dependencies
= filter( ['undefined', 'registered'], dependencies
);
844 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
845 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
846 queue
[queue
.length
] = dependencies
[n
];
850 mediaWiki
.loader
.work();
853 function sortQuery(o
) {
854 var sorted
= {}, key
, a
= [];
856 if ( o
.hasOwnProperty( key
) ) {
861 for ( key
= 0; key
< a
.length
; key
++ ) {
862 sorted
[a
[key
]] = o
[a
[key
]];
868 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
869 * to a query string of the form foo.bar,baz|bar.baz,quux
871 function buildModulesString( moduleMap
) {
873 for ( var prefix
in moduleMap
) {
874 var p
= prefix
=== '' ? '' : prefix
+ '.';
875 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
877 return arr
.join( '|' );
884 * Requests dependencies from server, loading and executing when things when ready.
886 this.work = function() {
887 // Appends a list of modules to the batch
888 for ( var q
= 0; q
< queue
.length
; q
++ ) {
889 // Only request modules which are undefined or registered
890 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
891 // Prevent duplicate entries
892 if ( $.inArray( queue
[q
], batch
) === -1 ) {
893 batch
[batch
.length
] = queue
[q
];
894 // Mark registered modules as loading
895 if ( queue
[q
] in registry
) {
896 registry
[queue
[q
]].state
= 'loading';
901 // Clean up the queue
903 // After document ready, handle the batch
904 if ( !suspended
&& batch
.length
) {
905 // Always order modules alphabetically to help reduce cache
906 // misses for otherwise identical content
908 // Build a list of request parameters
910 'skin': mediaWiki
.config
.get( 'skin' ),
911 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
912 'debug': mediaWiki
.config
.get( 'debug' )
914 // Extend request parameters with a list of modules in the batch
918 for ( var b
= 0; b
< batch
.length
; b
++ ) {
919 var group
= registry
[batch
[b
]].group
;
920 if ( !( group
in groups
) ) {
923 groups
[group
][groups
[group
].length
] = batch
[b
];
925 for ( var group
in groups
) {
926 // Calculate the highest timestamp
928 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
929 if ( registry
[groups
[group
][g
]].version
> version
) {
930 version
= registry
[groups
[group
][g
]].version
;
933 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
);
934 var reqBaseLength
= $.param( reqBase
).length
;
936 var limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
937 // We may need to split up the request to honor the query string length limit
938 // So build it piece by piece
939 var l
= reqBaseLength
+ 9; // '&modules='.length == 9
941 reqs
[0] = {}; // { prefix: [ suffixes ] }
942 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
943 // Determine how many bytes this module would add to the query string
944 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' );
945 // Note that these substr() calls work even if lastDotIndex == -1
946 var prefix
= groups
[group
][i
].substr( 0, lastDotIndex
);
947 var suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 );
948 var bytesAdded
= prefix
in reqs
[r
] ?
949 suffix
.length
+ 3 : // '%2C'.length == 3
950 groups
[group
][i
].length
+ 3; // '%7C'.length == 3
952 // If the request would become too long, create a new one,
953 // but don't create empty requests
954 if ( limit
> 0 && reqs
[r
] != {} && l
+ bytesAdded
> limit
) {
955 // This request would become too long, create a new one
958 l
= reqBaseLength
+ 9;
960 if ( !( prefix
in reqs
[r
] ) ) {
961 reqs
[r
][prefix
] = [];
963 reqs
[r
][prefix
].push( suffix
);
966 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
967 requests
[requests
.length
] = $.extend(
968 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
972 // Clear the batch - this MUST happen before we append the
973 // script element to the body or it's possible that the script
974 // will be locally cached, instantly load, and work the batch
975 // again, all before we've cleared it causing each request to
976 // include modules which are already loaded
978 // Asynchronously append a script tag to the end of the body
979 function getScriptTag() {
981 for ( var r
= 0; r
< requests
.length
; r
++ ) {
982 requests
[r
] = sortQuery( requests
[r
] );
983 // Build out the HTML
984 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
985 html
+= mediaWiki
.html
.element( 'script',
986 { type
: 'text/javascript', src
: src
}, '' );
990 // Load asynchronously after documument ready
992 setTimeout( function() { $( 'body' ).append( getScriptTag() ); }, 0 );
994 document
.write( getScriptTag() );
1000 * Registers a module, letting the system know about it and its
1001 * dependencies. loader.js files contain calls to this function.
1003 this.register = function( module
, version
, dependencies
, group
) {
1004 // Allow multiple registration
1005 if ( typeof module
=== 'object' ) {
1006 for ( var m
= 0; m
< module
.length
; m
++ ) {
1007 if ( typeof module
[m
] === 'string' ) {
1008 mediaWiki
.loader
.register( module
[m
] );
1009 } else if ( typeof module
[m
] === 'object' ) {
1010 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
1016 if ( typeof module
!== 'string' ) {
1017 throw new Error( 'module must be a string, not a ' + typeof module
);
1019 if ( typeof registry
[module
] !== 'undefined' ) {
1020 throw new Error( 'module already implemeneted: ' + module
);
1022 // List the module as registered
1023 registry
[module
] = {
1024 'state': 'registered',
1025 'group': typeof group
=== 'string' ? group
: null,
1027 'version': typeof version
!== 'undefined' ? parseInt( version
, 10 ) : 0
1029 if ( typeof dependencies
=== 'string' ) {
1030 // Allow dependencies to be given as a single module name
1031 registry
[module
].dependencies
= [dependencies
];
1032 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1033 // Allow dependencies to be given as an array of module names
1034 // or a function which returns an array
1035 registry
[module
].dependencies
= dependencies
;
1040 * Implements a module, giving the system a course of action to take
1041 * upon loading. Results of a request for one or more modules contain
1042 * calls to this function.
1044 this.implement = function( module
, script
, style
, localization
) {
1045 // Automatically register module
1046 if ( typeof registry
[module
] === 'undefined' ) {
1047 mediaWiki
.loader
.register( module
);
1050 if ( !$.isFunction( script
) ) {
1051 throw new Error( 'script must be a function, not a ' + typeof script
);
1053 if ( typeof style
!== 'undefined'
1054 && typeof style
!== 'string'
1055 && typeof style
!== 'object' )
1057 throw new Error( 'style must be a string or object, not a ' + typeof style
);
1059 if ( typeof localization
!== 'undefined'
1060 && typeof localization
!== 'object' )
1062 throw new Error( 'localization must be an object, not a ' + typeof localization
);
1064 if ( typeof registry
[module
] !== 'undefined'
1065 && typeof registry
[module
].script
!== 'undefined' )
1067 throw new Error( 'module already implemeneted: ' + module
);
1069 // Mark module as loaded
1070 registry
[module
].state
= 'loaded';
1071 // Attach components
1072 registry
[module
].script
= script
;
1073 if ( typeof style
=== 'string'
1074 || typeof style
=== 'object' && !( style
instanceof Array
) )
1076 registry
[module
].style
= style
;
1078 if ( typeof localization
=== 'object' ) {
1079 registry
[module
].messages
= localization
;
1081 // Execute or queue callback
1083 filter( ['ready'], registry
[module
].dependencies
),
1084 registry
[module
].dependencies
) )
1093 * Executes a function as soon as one or more required modules are ready
1095 * @param dependencies string or array of strings of modules names the callback
1096 * dependencies to be ready before
1098 * @param ready function callback to execute when all dependencies are ready (optional)
1099 * @param error function callback to execute when if dependencies have a errors (optional)
1101 this.using = function( dependencies
, ready
, error
) {
1103 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
1104 throw new Error( 'dependencies must be a string or an array, not a ' +
1105 typeof dependencies
);
1107 // Allow calling with a single dependency as a string
1108 if ( typeof dependencies
=== 'string' ) {
1109 dependencies
= [dependencies
];
1111 // Resolve entire dependency map
1112 dependencies
= resolve( dependencies
);
1113 // If all dependencies are met, execute ready immediately
1114 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1115 if ( $.isFunction( ready
) ) {
1119 // If any dependencies have errors execute error immediately
1120 else if ( filter( ['error'], dependencies
).length
) {
1121 if ( $.isFunction( error
) ) {
1125 // Since some dependencies are not yet ready, queue up a request
1127 request( dependencies
, ready
, error
);
1132 * Loads an external script or one or more modules for future use
1134 * @param modules mixed either the name of a module, array of modules,
1135 * or a URL of an external script or style
1136 * @param type string mime-type to use if calling with a URL of an
1137 * external script or style; acceptable values are "text/css" and
1138 * "text/javascript"; if no type is provided, text/javascript is
1141 this.load = function( modules
, type
) {
1143 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1144 throw new Error( 'modules must be a string or an array, not a ' +
1147 // Allow calling with an external script or single dependency as a string
1148 if ( typeof modules
=== 'string' ) {
1149 // Support adding arbitrary external scripts
1150 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
1151 if ( type
=== 'text/css' ) {
1152 $( 'head' ).append( $( '<link />', {
1158 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
1159 var script
= mediaWiki
.html
.element( 'script',
1160 { type
: 'text/javascript', src
: modules
}, '' );
1162 $( 'body' ).append( script
);
1164 document
.write( script
);
1171 // Called with single module
1172 modules
= [modules
];
1174 // Resolve entire dependency map
1175 modules
= resolve( modules
);
1176 // If all modules are ready, nothing dependency be done
1177 if ( compare( filter( ['ready'], modules
), modules
) ) {
1180 // If any modules have errors return false
1181 else if ( filter( ['error'], modules
).length
) {
1184 // Since some modules are not yet ready, queue up a request
1192 * Flushes the request queue and begin executing load requests on demand
1194 this.go = function() {
1196 mediaWiki
.loader
.work();
1200 * Changes the state of a module
1202 * @param module string module name or object of module name/state pairs
1203 * @param state string state name
1205 this.state = function( module
, state
) {
1206 if ( typeof module
=== 'object' ) {
1207 for ( var m
in module
) {
1208 mediaWiki
.loader
.state( m
, module
[m
] );
1212 if ( !( module
in registry
) ) {
1213 mediaWiki
.loader
.register( module
);
1215 registry
[module
].state
= state
;
1219 * Gets the version of a module
1221 * @param module string name of module to get version for
1223 this.version = function( module
) {
1224 if ( module
in registry
&& 'version' in registry
[module
] ) {
1225 return formatVersionNumber( registry
[module
].version
);
1230 /* Cache document ready status */
1232 $(document
).ready( function() { ready
= true; } );
1235 /** HTML construction helper functions */
1236 this.html
= new ( function () {
1237 var escapeCallback = function( s
) {
1253 * Escape a string for HTML. Converts special characters to HTML entities.
1254 * @param s The string to escape
1256 this.escape = function( s
) {
1257 return s
.replace( /['"<>&]/g, escapeCallback
);
1261 * Wrapper object for raw HTML passed to mw.html.element().
1263 this.Raw = function( value
) {
1268 * Wrapper object for CDATA element contents passed to mw.html.element()
1270 this.Cdata = function( value
) {
1275 * Create an HTML element string, with safe escaping.
1277 * @param name The tag name.
1278 * @param attrs An object with members mapping element names to values
1279 * @param contents The contents of the element. May be either:
1280 * - string: The string is escaped.
1281 * - null or undefined: The short closing form is used, e.g. <br/>.
1282 * - this.Raw: The value attribute is included without escaping.
1283 * - this.Cdata: The value attribute is included, and an exception is
1284 * thrown if it contains an illegal ETAGO delimiter.
1285 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1289 * return h.element( 'div', {},
1290 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1291 * Returns <div><img src="<"/></div>
1293 this.element = function( name
, attrs
, contents
) {
1295 for ( var attrName
in attrs
) {
1296 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1298 if ( typeof contents
== 'undefined' || contents
=== null ) {
1305 if ( typeof contents
=== 'string') {
1307 s
+= this.escape( contents
);
1308 } else if ( contents
instanceof this.Raw
) {
1309 // Raw HTML inclusion
1310 s
+= contents
.value
;
1311 } else if ( contents
instanceof this.Cdata
) {
1313 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1314 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1316 s
+= contents
.value
;
1318 throw new Error( 'mw.html.element: Invalid type of contents' );
1320 s
+= '</' + name
+ '>';
1326 /* Extension points */
1332 // Alias $j to jQuery for backwards compatibility
1334 window
.mw
= mediaWiki
;
1336 /* Auto-register from pre-loaded startup scripts */
1338 if ( $.isFunction( startUp
) ) {
1343 // Add jQuery Cookie to initial payload (used in mediaWiki.user)
1344 mw
.loader
.load( 'jquery.cookie' );