2 * Core MediaWiki JavaScript Library
5 // Attach to window and globally alias
6 window
.mw
= window
.mediaWiki
= new ( function( $ ) {
11 * @var object List of messages that have been requested to be loaded.
13 var messageQueue
= {};
15 /* Object constructors */
20 * Creates an object that can be read from or written to from prototype functions
21 * that allow both single and multiple variables at once.
23 * @param global boolean Whether to store the values in the global window
24 * object or a exclusively in the object property 'values'.
27 function Map( global
) {
28 this.values
= ( global
=== true ) ? window
: {};
34 * Get the value of one or multiple a keys.
36 * If called with no arguments, all values will be returned.
38 * @param selection mixed String key or array of keys to get values for.
39 * @param fallback mixed Value to use in case key(s) do not exist (optional).
40 * @return mixed If selection was a string returns the value or null,
41 * If selection was an array, returns an object of key/values (value is null if not found),
42 * If selection was not passed or invalid, will return the 'values' object member (be careful as
43 * objects are always passed by reference in JavaScript!).
44 * @return Values as a string or object, null if invalid/inexistant.
46 get: function( selection
, fallback
) {
47 if ( $.isArray( selection
) ) {
48 selection
= $.makeArray( selection
);
50 for ( var i
= 0; i
< selection
.length
; i
++ ) {
51 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
54 } else if ( typeof selection
=== 'string' ) {
55 if ( this.values
[selection
] === undefined ) {
56 if ( fallback
!== undefined ) {
61 return this.values
[selection
];
63 if ( selection
=== undefined ) {
66 return null; // invalid selection key
71 * Sets one or multiple key/value pairs.
73 * @param selection mixed String key or array of keys to set values for.
74 * @param value mixed Value to set (optional, only in use when key is a string)
75 * @return bool This returns true on success, false on failure.
77 set: function( selection
, value
) {
78 if ( $.isPlainObject( selection
) ) {
79 for ( var s
in selection
) {
80 this.values
[s
] = selection
[s
];
83 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
84 this.values
[selection
] = value
;
91 * Checks if one or multiple keys exist.
93 * @param selection mixed String key or array of keys to check
94 * @return boolean Existence of key(s)
96 exists: function( selection
) {
97 if ( typeof selection
=== 'object' ) {
98 for ( var s
= 0; s
< selection
.length
; s
++ ) {
99 if ( !( selection
[s
] in this.values
) ) {
105 return selection
in this.values
;
113 * Object constructor for messages,
114 * similar to the Message class in MediaWiki PHP.
116 * @param map Map Instance of mw.Map
118 * @param parameters Array
121 function Message( map
, key
, parameters
) {
122 this.format
= 'parse';
125 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
129 Message
.prototype = {
131 * Appends (does not replace) parameters for replacement to the .parameters property.
133 * @param parameters Array
136 params: function( parameters
) {
137 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
138 this.parameters
.push( parameters
[i
] );
144 * Converts message object to it's string form based on the state of format.
146 * @return string Message as a string in the current form or <key> if key does not exist.
148 toString: function() {
149 if ( !this.map
.exists( this.key
) ) {
150 // Return <key> if key does not exist
151 return '<' + this.key
+ '>';
153 var text
= this.map
.get( this.key
),
154 parameters
= this.parameters
;
156 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
157 var index
= parseInt( match
, 10 ) - 1;
158 return index
in parameters
? parameters
[index
] : '$' + match
;
161 if ( this.format
=== 'plain' ) {
164 if ( this.format
=== 'escaped' ) {
165 // According to Message.php this needs {{-transformation, which is
167 return mw
.html
.escape( text
);
170 /* This should be fixed up when we have a parser
171 if ( this.format === 'parse' && 'language' in mw ) {
172 text = mw.language.parse( text );
179 * Changes format to parse and converts message to string
181 * @return {string} String form of parsed message
184 this.format
= 'parse';
185 return this.toString();
189 * Changes format to plain and converts message to string
191 * @return {string} String form of plain message
194 this.format
= 'plain';
195 return this.toString();
199 * Changes the format to html escaped and converts message to string
201 * @return {string} String form of html escaped message
203 escaped: function() {
204 this.format
= 'escaped';
205 return this.toString();
209 * Checks if message exists
211 * @return {string} String form of parsed message
214 return this.map
.exists( this.key
);
221 * Dummy function which in debug mode can be replaced with a function that
222 * emulates console.log in console-less environments.
224 this.log = function() { };
227 * @var constructor Make the Map constructor publicly available.
232 * List of configuration values
234 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
235 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
236 * in the global window object.
243 * Empty object that plugins can be installed in.
248 * Localization system
250 this.messages
= new this.Map();
255 * Gets a message object, similar to wfMessage()
257 * @param key string Key of message to get
258 * @param parameter_1 mixed First argument in a list of variadic arguments,
259 * each a parameter for $N replacement in messages.
262 this.message = function( key
, parameter_1
/* [, parameter_2] */ ) {
264 // Support variadic arguments
265 if ( parameter_1
!== undefined ) {
266 parameters
= $.makeArray( arguments
);
271 return new Message( mw
.messages
, key
, parameters
);
275 * Gets a message string, similar to wfMsg()
277 * @param key string Key of message to get
278 * @param parameters mixed First argument in a list of variadic arguments,
279 * each a parameter for $N replacement in messages.
282 this.msg = function( key
, parameters
) {
283 return mw
.message
.apply( mw
.message
, arguments
).toString();
287 * Client-side module loader which integrates with the MediaWiki ResourceLoader
289 this.loader
= new ( function() {
291 /* Private Members */
294 * Mapping of registered modules
296 * The jquery module is pre-registered, because it must have already
297 * been provided for this object to have been built, and in debug mode
298 * jquery would have been provided through a unique loader request,
299 * making it impossible to hold back registration of jquery until after
302 * For exact details on support for script, style and messages, look at
303 * mw.loader.implement.
308 * 'version': ############## (unix timestamp),
309 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
310 * 'group': 'somegroup', (or) null,
311 * 'source': 'local', 'someforeignwiki', (or) null
312 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
315 * 'messages': { 'key': 'value' },
321 * Mapping of sources, keyed by source-id, values are objects.
325 * 'loadScript': 'http://foo.bar/w/load.php'
330 // List of modules which will be loaded as when ready
332 // List of modules to be loaded
334 // List of callback functions waiting for modules to be ready to be called
336 // Flag inidicating that document ready has occured
338 // Selector cache for the marker element. Use getMarker() to get/use the marker!
341 /* Private Methods */
343 function getMarker(){
348 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
349 if ( $marker
.length
) {
352 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
353 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
358 function compare( a
, b
) {
359 if ( a
.length
!== b
.length
) {
362 for ( var i
= 0; i
< b
.length
; i
++ ) {
363 if ( $.isArray( a
[i
] ) ) {
364 if ( !compare( a
[i
], b
[i
] ) ) {
368 if ( a
[i
] !== b
[i
] ) {
376 * Generates an ISO8601 "basic" string from a UNIX timestamp
378 function formatVersionNumber( timestamp
) {
379 var pad = function( a
, b
, c
) {
380 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
383 d
.setTime( timestamp
* 1000 );
385 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
386 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
391 * Recursively resolves dependencies and detects circular references
393 function recurse( module
, resolved
, unresolved
) {
394 if ( registry
[module
] === undefined ) {
395 throw new Error( 'Unknown dependency: ' + module
);
397 // Resolves dynamic loader function and replaces it with its own results
398 if ( $.isFunction( registry
[module
].dependencies
) ) {
399 registry
[module
].dependencies
= registry
[module
].dependencies();
400 // Ensures the module's dependencies are always in an array
401 if ( typeof registry
[module
].dependencies
!== 'object' ) {
402 registry
[module
].dependencies
= [registry
[module
].dependencies
];
405 // Tracks down dependencies
406 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
407 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
408 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
410 'Circular reference detected: ' + module
+
411 ' -> ' + registry
[module
].dependencies
[n
]
414 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
417 resolved
[resolved
.length
] = module
;
418 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
422 * Gets a list of module names that a module depends on in their proper dependency order
424 * @param module string module name or array of string module names
425 * @return list of dependencies
426 * @throws Error if circular reference is detected
428 function resolve( module
) {
429 // Allow calling with an array of module names
430 if ( typeof module
=== 'object' ) {
432 for ( var m
= 0; m
< module
.length
; m
++ ) {
433 var dependencies
= resolve( module
[m
] );
434 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
435 modules
[modules
.length
] = dependencies
[n
];
439 } else if ( typeof module
=== 'string' ) {
440 // Undefined modules have no dependencies
441 if ( !( module
in registry
) ) {
445 recurse( module
, resolved
, [] );
448 throw new Error( 'Invalid module argument: ' + module
);
452 * Narrows a list of module names down to those matching a specific
453 * state. Possible states are 'undefined', 'registered', 'loading',
454 * 'loaded', or 'ready'
456 * @param states string or array of strings of module states to filter by
457 * @param modules array list of module names to filter (optional, all modules
458 * will be used by default)
459 * @return array list of filtered module names
461 function filter( states
, modules
) {
462 // Allow states to be given as a string
463 if ( typeof states
=== 'string' ) {
466 // If called without a list of modules, build and use a list of all modules
467 var list
= [], module
;
468 if ( modules
=== undefined ) {
470 for ( module
in registry
) {
471 modules
[modules
.length
] = module
;
474 // Build a list of modules which are in one of the specified states
475 for ( var s
= 0; s
< states
.length
; s
++ ) {
476 for ( var m
= 0; m
< modules
.length
; m
++ ) {
477 if ( registry
[modules
[m
]] === undefined ) {
478 // Module does not exist
479 if ( states
[s
] === 'undefined' ) {
481 list
[list
.length
] = modules
[m
];
484 // Module exists, check state
485 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
487 list
[list
.length
] = modules
[m
];
496 * Executes a loaded module, making it ready to use
498 * @param module string module name to execute
500 function execute( module
, callback
) {
501 if ( registry
[module
] === undefined ) {
502 throw new Error( 'Module has not been registered yet: ' + module
);
503 } else if ( registry
[module
].state
=== 'registered' ) {
504 throw new Error( 'Module has not been requested from the server yet: ' + module
);
505 } else if ( registry
[module
].state
=== 'loading' ) {
506 throw new Error( 'Module has not completed loading yet: ' + module
);
507 } else if ( registry
[module
].state
=== 'ready' ) {
508 throw new Error( 'Module has already been loaded: ' + module
);
512 if ( $.isPlainObject( registry
[module
].style
) ) {
513 for ( var media
in registry
[module
].style
) {
514 style
= registry
[module
].style
[media
];
515 if ( $.isArray( style
) ) {
516 for ( var i
= 0; i
< style
.length
; i
++ ) {
517 getMarker().before( mw
.html
.element( 'link', {
523 } else if ( typeof style
=== 'string' ) {
524 getMarker().before( mw
.html
.element( 'style', {
527 }, new mw
.html
.Cdata( style
) ) );
531 // Add localizations to message system
532 if ( $.isPlainObject( registry
[module
].messages
) ) {
533 mw
.messages
.set( registry
[module
].messages
);
537 var script
= registry
[module
].script
,
538 markModuleReady = function() {
539 registry
[module
].state
= 'ready';
540 handlePending( module
);
541 if ( $.isFunction( callback
) ) {
546 if ( $.isArray( script
) ) {
548 if ( script
.length
=== 0 ) {
549 // No scripts in this module? Let's dive out early.
552 for ( var i
= 0; i
< script
.length
; i
++ ) {
553 registry
[module
].state
= 'loading';
554 addScript( script
[i
], function() {
555 if ( ++done
=== script
.length
) {
560 } else if ( $.isFunction( script
) ) {
565 // This needs to NOT use mw.log because these errors are common in production mode
566 // and not in debug mode, such as when a symbol that should be global isn't exported
567 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
568 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
570 registry
[module
].state
= 'error';
576 * Automatically executes jobs and modules which are pending with satistifed dependencies.
578 * This is used when dependencies are satisfied, such as when a module is executed.
580 function handlePending( module
) {
582 // Run jobs who's dependencies have just been met
583 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
585 filter( 'ready', jobs
[j
].dependencies
),
586 jobs
[j
].dependencies
) )
588 if ( $.isFunction( jobs
[j
].ready
) ) {
595 // Execute modules who's dependencies have just been met
596 for ( var r
in registry
) {
597 if ( registry
[r
].state
=== 'loaded' ) {
599 filter( ['ready'], registry
[r
].dependencies
),
600 registry
[r
].dependencies
) )
607 // Run error callbacks of jobs affected by this condition
608 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
609 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
610 if ( $.isFunction( jobs
[j
].error
) ) {
621 * Adds a dependencies to the queue with optional callbacks to be run
622 * when the dependencies are ready or fail
624 * @param dependencies string module name or array of string module names
625 * @param ready function callback to execute when all dependencies are ready
626 * @param error function callback to execute when any dependency fails
628 function request( dependencies
, ready
, error
) {
629 // Allow calling by single module name
630 if ( typeof dependencies
=== 'string' ) {
631 dependencies
= [dependencies
];
632 if ( dependencies
[0] in registry
) {
633 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
634 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
638 // Add ready and error callbacks if they were given
639 if ( arguments
.length
> 1 ) {
640 jobs
[jobs
.length
] = {
641 'dependencies': filter(
642 ['undefined', 'registered', 'loading', 'loaded'],
649 // Queue up any dependencies that are undefined or registered
650 dependencies
= filter( ['undefined', 'registered'], dependencies
);
651 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
652 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
653 queue
[queue
.length
] = dependencies
[n
];
660 function sortQuery(o
) {
661 var sorted
= {}, key
, a
= [];
663 if ( o
.hasOwnProperty( key
) ) {
668 for ( key
= 0; key
< a
.length
; key
++ ) {
669 sorted
[a
[key
]] = o
[a
[key
]];
675 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
676 * to a query string of the form foo.bar,baz|bar.baz,quux
678 function buildModulesString( moduleMap
) {
680 for ( var prefix
in moduleMap
) {
681 p
= prefix
=== '' ? '' : prefix
+ '.';
682 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
684 return arr
.join( '|' );
688 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
689 * depending on whether document-ready has occured yet.
691 * @param src String: URL to script, will be used as the src attribute in the script tag
692 * @param callback Function: Optional callback which will be run when the script is done
694 function addScript( src
, callback
) {
695 var done
= false, script
;
697 // jQuery's getScript method is NOT better than doing this the old-fassioned way
698 // because jQuery will eval the script's code, and errors will not have sane
700 script
= document
.createElement( 'script' );
701 script
.setAttribute( 'src', src
);
702 script
.setAttribute( 'type', 'text/javascript' );
703 if ( $.isFunction( callback
) ) {
704 // Attach handlers for all browsers -- this is based on jQuery.ajax
705 script
.onload
= script
.onreadystatechange = function() {
711 || /loaded|complete/.test( script
.readyState
)
717 // Handle memory leak in IE
718 script
.onload
= script
.onreadystatechange
= null;
722 if ( script
.parentNode
) {
723 script
.parentNode
.removeChild( script
);
726 // Dereference the script
731 document
.body
.appendChild( script
);
733 document
.write( mw
.html
.element(
734 'script', { 'type': 'text/javascript', 'src': src
}, ''
736 if ( $.isFunction( callback
) ) {
737 // Document.write is synchronous, so this is called when it's done
744 * Asynchronously append a script tag to the end of the body
745 * that invokes load.php
746 * @param moduleMap {Object}: Module map, see buildModulesString()
747 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
748 * @param sourceLoadScript {String}: URL of load.php
750 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
751 var request
= $.extend(
752 { 'modules': buildModulesString( moduleMap
) },
755 request
= sortQuery( request
);
756 // Asynchronously append a script tag to the end of the body
757 // Append &* to avoid triggering the IE6 extension check
758 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*' );
764 * Requests dependencies from server, loading and executing when things when ready.
766 this.work = function() {
767 // Build a list of request parameters common to all requests.
769 skin
: mw
.config
.get( 'skin' ),
770 lang
: mw
.config
.get( 'wgUserLanguage' ),
771 debug
: mw
.config
.get( 'debug' )
773 // Split module batch by source and by group.
775 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
777 // Appends a list of modules from the queue to the batch
778 for ( var q
= 0; q
< queue
.length
; q
++ ) {
779 // Only request modules which are undefined or registered
780 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
=== 'registered' ) {
781 // Prevent duplicate entries
782 if ( $.inArray( queue
[q
], batch
) === -1 ) {
783 batch
[batch
.length
] = queue
[q
];
784 // Mark registered modules as loading
785 if ( queue
[q
] in registry
) {
786 registry
[queue
[q
]].state
= 'loading';
791 // Early exit if there's nothing to load...
792 if ( !batch
.length
) {
796 // The queue has been processed into the batch, clear up the queue.
799 // Always order modules alphabetically to help reduce cache
800 // misses for otherwise identical content.
803 // Split batch by source and by group.
804 for ( var b
= 0; b
< batch
.length
; b
++ ) {
805 var bSource
= registry
[batch
[b
]].source
,
806 bGroup
= registry
[batch
[b
]].group
;
807 if ( !( bSource
in splits
) ) {
808 splits
[bSource
] = {};
810 if ( !( bGroup
in splits
[bSource
] ) ) {
811 splits
[bSource
][bGroup
] = [];
813 var bSourceGroup
= splits
[bSource
][bGroup
];
814 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
817 // Clear the batch - this MUST happen before we append any
818 // script elements to the body or it's possible that a script
819 // will be locally cached, instantly load, and work the batch
820 // again, all before we've cleared it causing each request to
821 // include modules which are already loaded.
824 var source
, group
, modules
, maxVersion
, sourceLoadScript
;
826 for ( source
in splits
) {
828 sourceLoadScript
= sources
[source
].loadScript
;
830 for ( group
in splits
[source
] ) {
832 // Cache access to currently selected list of
833 // modules for this group from this source.
834 modules
= splits
[source
][group
];
836 // Calculate the highest timestamp
838 for ( var g
= 0; g
< modules
.length
; g
++ ) {
839 if ( registry
[modules
[g
]].version
> maxVersion
) {
840 maxVersion
= registry
[modules
[g
]].version
;
844 var currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
),
845 currReqBaseLength
= $.param( currReqBase
).length
,
847 // We may need to split up the request to honor the query string length limit,
848 // so build it piece by piece.
849 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
851 moduleMap
= {}; // { prefix: [ suffixes ] }
853 for ( var i
= 0; i
< modules
.length
; i
++ ) {
854 // Determine how many bytes this module would add to the query string
855 var lastDotIndex
= modules
[i
].lastIndexOf( '.' ),
856 // Note that these substr() calls work even if lastDotIndex == -1
857 prefix
= modules
[i
].substr( 0, lastDotIndex
),
858 suffix
= modules
[i
].substr( lastDotIndex
+ 1 ),
859 bytesAdded
= prefix
in moduleMap
860 ? suffix
.length
+ 3 // '%2C'.length == 3
861 : modules
[i
].length
+ 3; // '%7C'.length == 3
863 // If the request would become too long, create a new one,
864 // but don't create empty requests
865 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
866 // This request would become too long, create a new one
867 // and fire off the old one
868 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
870 l
= currReqBaseLength
+ 9;
872 if ( !( prefix
in moduleMap
) ) {
873 moduleMap
[prefix
] = [];
875 moduleMap
[prefix
].push( suffix
);
878 // If there's anything left in moduleMap, request that too
879 if ( !$.isEmptyObject( moduleMap
) ) {
880 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
889 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
890 * @param props {Object}: Object containing only the loadScript property which is a url to
891 * the load.php location of the source.
894 this.addSource = function( id
, props
) {
895 // Allow multiple additions
896 if ( typeof id
=== 'object' ) {
897 for ( var source
in id
) {
898 mw
.loader
.addSource( source
, id
[source
] );
903 if ( sources
[id
] !== undefined ) {
904 throw new Error( 'source already registered: ' + id
);
913 * Registers a module, letting the system know about it and its
914 * properties. Startup modules contain calls to this function.
916 * @param module {String}: Module name
917 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
918 * @param dependencies {String|Array|Function}: One string or array of strings of module
919 * names on which this module depends, or a function that returns that array.
920 * @param group {String}: Group which the module is in (optional, defaults to null)
921 * @param source {String}: Name of the source. Defaults to local.
923 this.register = function( module
, version
, dependencies
, group
, source
) {
924 // Allow multiple registration
925 if ( typeof module
=== 'object' ) {
926 for ( var m
= 0; m
< module
.length
; m
++ ) {
927 // module is an array of module names
928 if ( typeof module
[m
] === 'string' ) {
929 mw
.loader
.register( module
[m
] );
930 // module is an array of arrays
931 } else if ( typeof module
[m
] === 'object' ) {
932 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
938 if ( typeof module
!== 'string' ) {
939 throw new Error( 'module must be a string, not a ' + typeof module
);
941 if ( registry
[module
] !== undefined ) {
942 throw new Error( 'module already implemented: ' + module
);
944 // List the module as registered
946 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
948 'group': typeof group
=== 'string' ? group
: null,
949 'source': typeof source
=== 'string' ? source
: 'local',
950 'state': 'registered'
952 if ( typeof dependencies
=== 'string' ) {
953 // Allow dependencies to be given as a single module name
954 registry
[module
].dependencies
= [dependencies
];
955 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
956 // Allow dependencies to be given as an array of module names
957 // or a function which returns an array
958 registry
[module
].dependencies
= dependencies
;
963 * Implements a module, giving the system a course of action to take
964 * upon loading. Results of a request for one or more modules contain
965 * calls to this function.
967 * All arguments are required.
969 * @param module String: Name of module
970 * @param script Mixed: Function of module code or String of URL to be used as the src
971 * attribute when adding a script element to the body
972 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
973 * keyed by media-type
974 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
976 this.implement = function( module
, script
, style
, msgs
) {
978 if ( typeof module
!== 'string' ) {
979 throw new Error( 'module must be a string, not a ' + typeof module
);
981 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
982 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
984 if ( !$.isPlainObject( style
) ) {
985 throw new Error( 'style must be an object, not a ' + typeof style
);
987 if ( !$.isPlainObject( msgs
) ) {
988 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
990 // Automatically register module
991 if ( registry
[module
] === undefined ) {
992 mw
.loader
.register( module
);
994 // Check for duplicate implementation
995 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
996 throw new Error( 'module already implemeneted: ' + module
);
998 // Mark module as loaded
999 registry
[module
].state
= 'loaded';
1000 // Attach components
1001 registry
[module
].script
= script
;
1002 registry
[module
].style
= style
;
1003 registry
[module
].messages
= msgs
;
1004 // Execute or queue callback
1006 filter( ['ready'], registry
[module
].dependencies
),
1007 registry
[module
].dependencies
) )
1016 * Executes a function as soon as one or more required modules are ready
1018 * @param dependencies string or array of strings of modules names the callback
1019 * dependencies to be ready before executing
1020 * @param ready function callback to execute when all dependencies are ready (optional)
1021 * @param error function callback to execute when if dependencies have a errors (optional)
1023 this.using = function( dependencies
, ready
, error
) {
1024 var tod
= typeof dependencies
;
1026 if ( tod
!== 'object' && tod
!== 'string' ) {
1027 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1029 // Allow calling with a single dependency as a string
1030 if ( tod
=== 'string' ) {
1031 dependencies
= [dependencies
];
1033 // Resolve entire dependency map
1034 dependencies
= resolve( dependencies
);
1035 // If all dependencies are met, execute ready immediately
1036 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1037 if ( $.isFunction( ready
) ) {
1041 // If any dependencies have errors execute error immediately
1042 else if ( filter( ['error'], dependencies
).length
) {
1043 if ( $.isFunction( error
) ) {
1047 // Since some dependencies are not yet ready, queue up a request
1049 request( dependencies
, ready
, error
);
1054 * Loads an external script or one or more modules for future use
1056 * @param modules mixed either the name of a module, array of modules,
1057 * or a URL of an external script or style
1058 * @param type string mime-type to use if calling with a URL of an
1059 * external script or style; acceptable values are "text/css" and
1060 * "text/javascript"; if no type is provided, text/javascript is assumed.
1062 this.load = function( modules
, type
) {
1064 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1065 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1067 // Allow calling with an external script or single dependency as a string
1068 if ( typeof modules
=== 'string' ) {
1069 // Support adding arbitrary external scripts
1070 if ( modules
.substr( 0, 7 ) === 'http://' || modules
.substr( 0, 8 ) === 'https://' || modules
.substr( 0, 2 ) === '//' ) {
1071 if ( type
=== 'text/css' ) {
1072 $( 'head' ).append( $( '<link/>', {
1078 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
1079 addScript( modules
);
1085 // Called with single module
1086 modules
= [modules
];
1088 // Resolve entire dependency map
1089 modules
= resolve( modules
);
1090 // If all modules are ready, nothing dependency be done
1091 if ( compare( filter( ['ready'], modules
), modules
) ) {
1094 // If any modules have errors return false
1095 else if ( filter( ['error'], modules
).length
) {
1098 // Since some modules are not yet ready, queue up a request
1106 * Changes the state of a module
1108 * @param module string module name or object of module name/state pairs
1109 * @param state string state name
1111 this.state = function( module
, state
) {
1112 if ( typeof module
=== 'object' ) {
1113 for ( var m
in module
) {
1114 mw
.loader
.state( m
, module
[m
] );
1118 if ( !( module
in registry
) ) {
1119 mw
.loader
.register( module
);
1121 registry
[module
].state
= state
;
1125 * Gets the version of a module
1127 * @param module string name of module to get version for
1129 this.getVersion = function( module
) {
1130 if ( module
in registry
&& 'version' in registry
[module
] ) {
1131 return formatVersionNumber( registry
[module
].version
);
1137 * @deprecated use mw.loader.getVersion() instead
1139 this.version = function() {
1140 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1144 * Gets the state of a module
1146 * @param module string name of module to get state for
1148 this.getState = function( module
) {
1149 if ( module
in registry
&& 'state' in registry
[module
] ) {
1150 return registry
[module
].state
;
1155 /* Cache document ready status */
1157 $(document
).ready( function() { ready
= true; } );
1160 /** HTML construction helper functions */
1161 this.html
= new ( function () {
1162 var escapeCallback = function( s
) {
1178 * Escape a string for HTML. Converts special characters to HTML entities.
1179 * @param s The string to escape
1181 this.escape = function( s
) {
1182 return s
.replace( /['"<>&]/g, escapeCallback
);
1186 * Wrapper object for raw HTML passed to mw.html.element().
1188 this.Raw = function( value
) {
1193 * Wrapper object for CDATA element contents passed to mw.html.element()
1195 this.Cdata = function( value
) {
1200 * Create an HTML element string, with safe escaping.
1202 * @param name The tag name.
1203 * @param attrs An object with members mapping element names to values
1204 * @param contents The contents of the element. May be either:
1205 * - string: The string is escaped.
1206 * - null or undefined: The short closing form is used, e.g. <br/>.
1207 * - this.Raw: The value attribute is included without escaping.
1208 * - this.Cdata: The value attribute is included, and an exception is
1209 * thrown if it contains an illegal ETAGO delimiter.
1210 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1214 * return h.element( 'div', {},
1215 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1216 * Returns <div><img src="<"/></div>
1218 this.element = function( name
, attrs
, contents
) {
1220 for ( var attrName
in attrs
) {
1221 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1223 if ( contents
=== undefined || contents
=== null ) {
1230 if ( typeof contents
=== 'string' ) {
1232 s
+= this.escape( contents
);
1233 } else if ( contents
instanceof this.Raw
) {
1234 // Raw HTML inclusion
1235 s
+= contents
.value
;
1236 } else if ( contents
instanceof this.Cdata
) {
1238 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1239 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1241 s
+= contents
.value
;
1243 throw new Error( 'mw.html.element: Invalid type of contents' );
1245 s
+= '</' + name
+ '>';
1250 /* Extension points */
1256 // Alias $j to jQuery for backwards compatibility
1259 // Auto-register from pre-loaded startup scripts
1260 if ( jQuery
.isFunction( startUp
) ) {