cf89e03511b5aa614203147830daa1b49e88ab37
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
= 'plain';
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() {
150 if ( !this.map
.exists( this.key
) ) {
151 // Use <key> as text if key does not exist
152 if ( this.format
!== 'plain' ) {
153 // format 'escape' and 'parse' need to have the brackets and key html escaped
154 return mw
.html
.escape( '<' + this.key
+ '>' );
156 return '<' + this.key
+ '>';
158 var text
= this.map
.get( this.key
),
159 parameters
= this.parameters
;
161 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
162 var index
= parseInt( match
, 10 ) - 1;
163 return index
in parameters
? parameters
[index
] : '$' + match
;
166 if ( this.format
=== 'plain' ) {
169 if ( this.format
=== 'escaped' ) {
170 // According to Message.php this needs {{-transformation, which is
172 return mw
.html
.escape( text
);
175 /* This should be fixed up when we have a parser
176 if ( this.format === 'parse' && 'language' in mw ) {
177 text = mw.language.parse( text );
184 * Changes format to parse and converts message to string
186 * @return {string} String form of parsed message
189 this.format
= 'parse';
190 return this.toString();
194 * Changes format to plain and converts message to string
196 * @return {string} String form of plain message
199 this.format
= 'plain';
200 return this.toString();
204 * Changes the format to html escaped and converts message to string
206 * @return {string} String form of html escaped message
208 escaped: function() {
209 this.format
= 'escaped';
210 return this.toString();
214 * Checks if message exists
216 * @return {string} String form of parsed message
219 return this.map
.exists( this.key
);
226 * Dummy function which in debug mode can be replaced with a function that
227 * emulates console.log in console-less environments.
229 this.log = function() { };
232 * @var constructor Make the Map constructor publicly available.
237 * List of configuration values
239 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
240 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
241 * in the global window object.
248 * Empty object that plugins can be installed in.
253 * Localization system
255 this.messages
= new this.Map();
260 * Gets a message object, similar to wfMessage()
262 * @param key string Key of message to get
263 * @param parameter_1 mixed First argument in a list of variadic arguments,
264 * each a parameter for $N replacement in messages.
267 this.message = function( key
, parameter_1
/* [, parameter_2] */ ) {
269 // Support variadic arguments
270 if ( parameter_1
!== undefined ) {
271 parameters
= $.makeArray( arguments
);
276 return new Message( mw
.messages
, key
, parameters
);
280 * Gets a message string, similar to wfMsg()
282 * @param key string Key of message to get
283 * @param parameters mixed First argument in a list of variadic arguments,
284 * each a parameter for $N replacement in messages.
287 this.msg = function( key
, parameters
) {
288 return mw
.message
.apply( mw
.message
, arguments
).toString();
292 * Client-side module loader which integrates with the MediaWiki ResourceLoader
294 this.loader
= new ( function() {
296 /* Private Members */
299 * Mapping of registered modules
301 * The jquery module is pre-registered, because it must have already
302 * been provided for this object to have been built, and in debug mode
303 * jquery would have been provided through a unique loader request,
304 * making it impossible to hold back registration of jquery until after
307 * For exact details on support for script, style and messages, look at
308 * mw.loader.implement.
313 * 'version': ############## (unix timestamp),
314 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
315 * 'group': 'somegroup', (or) null,
316 * 'source': 'local', 'someforeignwiki', (or) null
317 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
320 * 'messages': { 'key': 'value' },
326 * Mapping of sources, keyed by source-id, values are objects.
330 * 'loadScript': 'http://foo.bar/w/load.php'
335 // List of modules which will be loaded as when ready
337 // List of modules to be loaded
339 // List of callback functions waiting for modules to be ready to be called
341 // Flag inidicating that document ready has occured
343 // Selector cache for the marker element. Use getMarker() to get/use the marker!
346 /* Private Methods */
348 function getMarker(){
353 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
354 if ( $marker
.length
) {
357 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
358 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
363 function compare( a
, b
) {
364 if ( a
.length
!== b
.length
) {
367 for ( var i
= 0; i
< b
.length
; i
++ ) {
368 if ( $.isArray( a
[i
] ) ) {
369 if ( !compare( a
[i
], b
[i
] ) ) {
373 if ( a
[i
] !== b
[i
] ) {
381 * Generates an ISO8601 "basic" string from a UNIX timestamp
383 function formatVersionNumber( timestamp
) {
384 var pad = function( a
, b
, c
) {
385 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
388 d
.setTime( timestamp
* 1000 );
390 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
391 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
396 * Recursively resolves dependencies and detects circular references
398 function recurse( module
, resolved
, unresolved
) {
399 if ( registry
[module
] === undefined ) {
400 throw new Error( 'Unknown dependency: ' + module
);
402 // Resolves dynamic loader function and replaces it with its own results
403 if ( $.isFunction( registry
[module
].dependencies
) ) {
404 registry
[module
].dependencies
= registry
[module
].dependencies();
405 // Ensures the module's dependencies are always in an array
406 if ( typeof registry
[module
].dependencies
!== 'object' ) {
407 registry
[module
].dependencies
= [registry
[module
].dependencies
];
410 // Tracks down dependencies
411 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
412 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
413 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
415 'Circular reference detected: ' + module
+
416 ' -> ' + registry
[module
].dependencies
[n
]
419 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
422 resolved
[resolved
.length
] = module
;
423 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
427 * Gets a list of module names that a module depends on in their proper dependency order
429 * @param module string module name or array of string module names
430 * @return list of dependencies
431 * @throws Error if circular reference is detected
433 function resolve( module
) {
434 // Allow calling with an array of module names
435 if ( typeof module
=== 'object' ) {
437 for ( var m
= 0; m
< module
.length
; m
++ ) {
438 var dependencies
= resolve( module
[m
] );
439 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
440 modules
[modules
.length
] = dependencies
[n
];
444 } else if ( typeof module
=== 'string' ) {
445 // Undefined modules have no dependencies
446 if ( !( module
in registry
) ) {
450 recurse( module
, resolved
, [] );
453 throw new Error( 'Invalid module argument: ' + module
);
457 * Narrows a list of module names down to those matching a specific
458 * state. Possible states are 'undefined', 'registered', 'loading',
459 * 'loaded', or 'ready'
461 * @param states string or array of strings of module states to filter by
462 * @param modules array list of module names to filter (optional, all modules
463 * will be used by default)
464 * @return array list of filtered module names
466 function filter( states
, modules
) {
467 // Allow states to be given as a string
468 if ( typeof states
=== 'string' ) {
471 // If called without a list of modules, build and use a list of all modules
472 var list
= [], module
;
473 if ( modules
=== undefined ) {
475 for ( module
in registry
) {
476 modules
[modules
.length
] = module
;
479 // Build a list of modules which are in one of the specified states
480 for ( var s
= 0; s
< states
.length
; s
++ ) {
481 for ( var m
= 0; m
< modules
.length
; m
++ ) {
482 if ( registry
[modules
[m
]] === undefined ) {
483 // Module does not exist
484 if ( states
[s
] === 'undefined' ) {
486 list
[list
.length
] = modules
[m
];
489 // Module exists, check state
490 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
492 list
[list
.length
] = modules
[m
];
501 * Executes a loaded module, making it ready to use
503 * @param module string module name to execute
505 function execute( module
, callback
) {
506 if ( registry
[module
] === undefined ) {
507 throw new Error( 'Module has not been registered yet: ' + module
);
508 } else if ( registry
[module
].state
=== 'registered' ) {
509 throw new Error( 'Module has not been requested from the server yet: ' + module
);
510 } else if ( registry
[module
].state
=== 'loading' ) {
511 throw new Error( 'Module has not completed loading yet: ' + module
);
512 } else if ( registry
[module
].state
=== 'ready' ) {
513 throw new Error( 'Module has already been loaded: ' + module
);
517 if ( $.isPlainObject( registry
[module
].style
) ) {
518 for ( var media
in registry
[module
].style
) {
519 style
= registry
[module
].style
[media
];
520 if ( $.isArray( style
) ) {
521 for ( var i
= 0; i
< style
.length
; i
++ ) {
522 getMarker().before( mw
.html
.element( 'link', {
528 } else if ( typeof style
=== 'string' ) {
529 getMarker().before( mw
.html
.element( 'style', {
532 }, new mw
.html
.Cdata( style
) ) );
536 // Add localizations to message system
537 if ( $.isPlainObject( registry
[module
].messages
) ) {
538 mw
.messages
.set( registry
[module
].messages
);
542 var script
= registry
[module
].script
,
543 markModuleReady = function() {
544 registry
[module
].state
= 'ready';
545 handlePending( module
);
546 if ( $.isFunction( callback
) ) {
551 if ( $.isArray( script
) ) {
553 if ( script
.length
=== 0 ) {
554 // No scripts in this module? Let's dive out early.
557 for ( var i
= 0; i
< script
.length
; i
++ ) {
558 registry
[module
].state
= 'loading';
559 addScript( script
[i
], function() {
560 if ( ++done
=== script
.length
) {
565 } else if ( $.isFunction( script
) ) {
570 // This needs to NOT use mw.log because these errors are common in production mode
571 // and not in debug mode, such as when a symbol that should be global isn't exported
572 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
573 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
575 registry
[module
].state
= 'error';
581 * Automatically executes jobs and modules which are pending with satistifed dependencies.
583 * This is used when dependencies are satisfied, such as when a module is executed.
585 function handlePending( module
) {
587 // Run jobs who's dependencies have just been met
588 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
590 filter( 'ready', jobs
[j
].dependencies
),
591 jobs
[j
].dependencies
) )
593 if ( $.isFunction( jobs
[j
].ready
) ) {
600 // Execute modules who's dependencies have just been met
601 for ( var r
in registry
) {
602 if ( registry
[r
].state
=== 'loaded' ) {
604 filter( ['ready'], registry
[r
].dependencies
),
605 registry
[r
].dependencies
) )
612 // Run error callbacks of jobs affected by this condition
613 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
614 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
615 if ( $.isFunction( jobs
[j
].error
) ) {
626 * Adds a dependencies to the queue with optional callbacks to be run
627 * when the dependencies are ready or fail
629 * @param dependencies string module name or array of string module names
630 * @param ready function callback to execute when all dependencies are ready
631 * @param error function callback to execute when any dependency fails
633 function request( dependencies
, ready
, error
) {
634 // Allow calling by single module name
635 if ( typeof dependencies
=== 'string' ) {
636 dependencies
= [dependencies
];
637 if ( dependencies
[0] in registry
) {
638 // Cache repetitively accessed deep level object member
639 var regItemDeps
= registry
[dependencies
[0]].dependencies
,
640 // Cache to avoid looped access to length property
641 regItemDepLen
= regItemDeps
.length
;
642 for ( var n
= 0; n
< regItemDepLen
; n
++ ) {
643 dependencies
[dependencies
.length
] = regItemDeps
[n
];
647 // Add ready and error callbacks if they were given
648 if ( arguments
.length
> 1 ) {
649 jobs
[jobs
.length
] = {
650 'dependencies': filter(
651 ['undefined', 'registered', 'loading', 'loaded'],
658 // Queue up any dependencies that are undefined or registered
659 dependencies
= filter( ['undefined', 'registered'], dependencies
);
660 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
661 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
662 queue
[queue
.length
] = dependencies
[n
];
669 function sortQuery(o
) {
670 var sorted
= {}, key
, a
= [];
672 if ( o
.hasOwnProperty( key
) ) {
677 for ( key
= 0; key
< a
.length
; key
++ ) {
678 sorted
[a
[key
]] = o
[a
[key
]];
684 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
685 * to a query string of the form foo.bar,baz|bar.baz,quux
687 function buildModulesString( moduleMap
) {
689 for ( var prefix
in moduleMap
) {
690 p
= prefix
=== '' ? '' : prefix
+ '.';
691 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
693 return arr
.join( '|' );
697 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
698 * depending on whether document-ready has occured yet.
700 * @param src String: URL to script, will be used as the src attribute in the script tag
701 * @param callback Function: Optional callback which will be run when the script is done
703 function addScript( src
, callback
) {
704 var done
= false, script
;
706 // jQuery's getScript method is NOT better than doing this the old-fassioned way
707 // because jQuery will eval the script's code, and errors will not have sane
709 script
= document
.createElement( 'script' );
710 script
.setAttribute( 'src', src
);
711 script
.setAttribute( 'type', 'text/javascript' );
712 if ( $.isFunction( callback
) ) {
713 // Attach handlers for all browsers -- this is based on jQuery.ajax
714 script
.onload
= script
.onreadystatechange = function() {
720 || /loaded|complete/.test( script
.readyState
)
726 // Handle memory leak in IE
727 script
.onload
= script
.onreadystatechange
= null;
731 if ( script
.parentNode
) {
732 script
.parentNode
.removeChild( script
);
735 // Dereference the script
740 document
.body
.appendChild( script
);
742 document
.write( mw
.html
.element(
743 'script', { 'type': 'text/javascript', 'src': src
}, ''
745 if ( $.isFunction( callback
) ) {
746 // Document.write is synchronous, so this is called when it's done
753 * Asynchronously append a script tag to the end of the body
754 * that invokes load.php
755 * @param moduleMap {Object}: Module map, see buildModulesString()
756 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
757 * @param sourceLoadScript {String}: URL of load.php
759 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
760 var request
= $.extend(
761 { 'modules': buildModulesString( moduleMap
) },
764 request
= sortQuery( request
);
765 // Asynchronously append a script tag to the end of the body
766 // Append &* to avoid triggering the IE6 extension check
767 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*' );
773 * Requests dependencies from server, loading and executing when things when ready.
775 this.work = function() {
776 // Build a list of request parameters common to all requests.
778 skin
: mw
.config
.get( 'skin' ),
779 lang
: mw
.config
.get( 'wgUserLanguage' ),
780 debug
: mw
.config
.get( 'debug' )
782 // Split module batch by source and by group.
784 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
786 // Appends a list of modules from the queue to the batch
787 for ( var q
= 0; q
< queue
.length
; q
++ ) {
788 // Only request modules which are undefined or registered
789 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
=== 'registered' ) {
790 // Prevent duplicate entries
791 if ( $.inArray( queue
[q
], batch
) === -1 ) {
792 batch
[batch
.length
] = queue
[q
];
793 // Mark registered modules as loading
794 if ( queue
[q
] in registry
) {
795 registry
[queue
[q
]].state
= 'loading';
800 // Early exit if there's nothing to load...
801 if ( !batch
.length
) {
805 // The queue has been processed into the batch, clear up the queue.
808 // Always order modules alphabetically to help reduce cache
809 // misses for otherwise identical content.
812 // Split batch by source and by group.
813 for ( var b
= 0; b
< batch
.length
; b
++ ) {
814 var bSource
= registry
[batch
[b
]].source
,
815 bGroup
= registry
[batch
[b
]].group
;
816 if ( !( bSource
in splits
) ) {
817 splits
[bSource
] = {};
819 if ( !( bGroup
in splits
[bSource
] ) ) {
820 splits
[bSource
][bGroup
] = [];
822 var bSourceGroup
= splits
[bSource
][bGroup
];
823 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
826 // Clear the batch - this MUST happen before we append any
827 // script elements to the body or it's possible that a script
828 // will be locally cached, instantly load, and work the batch
829 // again, all before we've cleared it causing each request to
830 // include modules which are already loaded.
833 var source
, group
, modules
, maxVersion
, sourceLoadScript
;
835 for ( source
in splits
) {
837 sourceLoadScript
= sources
[source
].loadScript
;
839 for ( group
in splits
[source
] ) {
841 // Cache access to currently selected list of
842 // modules for this group from this source.
843 modules
= splits
[source
][group
];
845 // Calculate the highest timestamp
847 for ( var g
= 0; g
< modules
.length
; g
++ ) {
848 if ( registry
[modules
[g
]].version
> maxVersion
) {
849 maxVersion
= registry
[modules
[g
]].version
;
853 var currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
),
854 currReqBaseLength
= $.param( currReqBase
).length
,
856 // We may need to split up the request to honor the query string length limit,
857 // so build it piece by piece.
858 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
860 moduleMap
= {}; // { prefix: [ suffixes ] }
862 for ( var i
= 0; i
< modules
.length
; i
++ ) {
863 // Determine how many bytes this module would add to the query string
864 var lastDotIndex
= modules
[i
].lastIndexOf( '.' ),
865 // Note that these substr() calls work even if lastDotIndex == -1
866 prefix
= modules
[i
].substr( 0, lastDotIndex
),
867 suffix
= modules
[i
].substr( lastDotIndex
+ 1 ),
868 bytesAdded
= prefix
in moduleMap
869 ? suffix
.length
+ 3 // '%2C'.length == 3
870 : modules
[i
].length
+ 3; // '%7C'.length == 3
872 // If the request would become too long, create a new one,
873 // but don't create empty requests
874 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
875 // This request would become too long, create a new one
876 // and fire off the old one
877 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
879 l
= currReqBaseLength
+ 9;
881 if ( !( prefix
in moduleMap
) ) {
882 moduleMap
[prefix
] = [];
884 moduleMap
[prefix
].push( suffix
);
887 // If there's anything left in moduleMap, request that too
888 if ( !$.isEmptyObject( moduleMap
) ) {
889 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
898 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
899 * @param props {Object}: Object containing only the loadScript property which is a url to
900 * the load.php location of the source.
903 this.addSource = function( id
, props
) {
904 // Allow multiple additions
905 if ( typeof id
=== 'object' ) {
906 for ( var source
in id
) {
907 mw
.loader
.addSource( source
, id
[source
] );
912 if ( sources
[id
] !== undefined ) {
913 throw new Error( 'source already registered: ' + id
);
922 * Registers a module, letting the system know about it and its
923 * properties. Startup modules contain calls to this function.
925 * @param module {String}: Module name
926 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
927 * @param dependencies {String|Array|Function}: One string or array of strings of module
928 * names on which this module depends, or a function that returns that array.
929 * @param group {String}: Group which the module is in (optional, defaults to null)
930 * @param source {String}: Name of the source. Defaults to local.
932 this.register = function( module
, version
, dependencies
, group
, source
) {
933 // Allow multiple registration
934 if ( typeof module
=== 'object' ) {
935 for ( var m
= 0; m
< module
.length
; m
++ ) {
936 // module is an array of module names
937 if ( typeof module
[m
] === 'string' ) {
938 mw
.loader
.register( module
[m
] );
939 // module is an array of arrays
940 } else if ( typeof module
[m
] === 'object' ) {
941 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
947 if ( typeof module
!== 'string' ) {
948 throw new Error( 'module must be a string, not a ' + typeof module
);
950 if ( registry
[module
] !== undefined ) {
951 throw new Error( 'module already implemented: ' + module
);
953 // List the module as registered
955 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
957 'group': typeof group
=== 'string' ? group
: null,
958 'source': typeof source
=== 'string' ? source
: 'local',
959 'state': 'registered'
961 if ( typeof dependencies
=== 'string' ) {
962 // Allow dependencies to be given as a single module name
963 registry
[module
].dependencies
= [dependencies
];
964 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
965 // Allow dependencies to be given as an array of module names
966 // or a function which returns an array
967 registry
[module
].dependencies
= dependencies
;
972 * Implements a module, giving the system a course of action to take
973 * upon loading. Results of a request for one or more modules contain
974 * calls to this function.
976 * All arguments are required.
978 * @param module String: Name of module
979 * @param script Mixed: Function of module code or String of URL to be used as the src
980 * attribute when adding a script element to the body
981 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
982 * keyed by media-type
983 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
985 this.implement = function( module
, script
, style
, msgs
) {
987 if ( typeof module
!== 'string' ) {
988 throw new Error( 'module must be a string, not a ' + typeof module
);
990 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
991 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
993 if ( !$.isPlainObject( style
) ) {
994 throw new Error( 'style must be an object, not a ' + typeof style
);
996 if ( !$.isPlainObject( msgs
) ) {
997 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
999 // Automatically register module
1000 if ( registry
[module
] === undefined ) {
1001 mw
.loader
.register( module
);
1003 // Check for duplicate implementation
1004 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1005 throw new Error( 'module already implemeneted: ' + module
);
1007 // Mark module as loaded
1008 registry
[module
].state
= 'loaded';
1009 // Attach components
1010 registry
[module
].script
= script
;
1011 registry
[module
].style
= style
;
1012 registry
[module
].messages
= msgs
;
1013 // Execute or queue callback
1015 filter( ['ready'], registry
[module
].dependencies
),
1016 registry
[module
].dependencies
) )
1025 * Executes a function as soon as one or more required modules are ready
1027 * @param dependencies string or array of strings of modules names the callback
1028 * dependencies to be ready before executing
1029 * @param ready function callback to execute when all dependencies are ready (optional)
1030 * @param error function callback to execute when if dependencies have a errors (optional)
1032 this.using = function( dependencies
, ready
, error
) {
1033 var tod
= typeof dependencies
;
1035 if ( tod
!== 'object' && tod
!== 'string' ) {
1036 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1038 // Allow calling with a single dependency as a string
1039 if ( tod
=== 'string' ) {
1040 dependencies
= [dependencies
];
1042 // Resolve entire dependency map
1043 dependencies
= resolve( dependencies
);
1044 // If all dependencies are met, execute ready immediately
1045 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1046 if ( $.isFunction( ready
) ) {
1050 // If any dependencies have errors execute error immediately
1051 else if ( filter( ['error'], dependencies
).length
) {
1052 if ( $.isFunction( error
) ) {
1056 // Since some dependencies are not yet ready, queue up a request
1058 request( dependencies
, ready
, error
);
1063 * Loads an external script or one or more modules for future use
1065 * @param modules mixed either the name of a module, array of modules,
1066 * or a URL of an external script or style
1067 * @param type string mime-type to use if calling with a URL of an
1068 * external script or style; acceptable values are "text/css" and
1069 * "text/javascript"; if no type is provided, text/javascript is assumed.
1071 this.load = function( modules
, type
) {
1073 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1074 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1076 // Allow calling with an external script or single dependency as a string
1077 if ( typeof modules
=== 'string' ) {
1078 // Support adding arbitrary external scripts
1079 if ( /^(https?:)?\/\//.test( modules
) ) {
1080 if ( type
=== 'text/css' ) {
1081 $( 'head' ).append( $( '<link/>', {
1087 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
1088 addScript( modules
);
1094 // Called with single module
1095 modules
= [modules
];
1097 // Resolve entire dependency map
1098 modules
= resolve( modules
);
1099 // If all modules are ready, nothing dependency be done
1100 if ( compare( filter( ['ready'], modules
), modules
) ) {
1103 // If any modules have errors return false
1104 else if ( filter( ['error'], modules
).length
) {
1107 // Since some modules are not yet ready, queue up a request
1115 * Changes the state of a module
1117 * @param module string module name or object of module name/state pairs
1118 * @param state string state name
1120 this.state = function( module
, state
) {
1121 if ( typeof module
=== 'object' ) {
1122 for ( var m
in module
) {
1123 mw
.loader
.state( m
, module
[m
] );
1127 if ( !( module
in registry
) ) {
1128 mw
.loader
.register( module
);
1130 registry
[module
].state
= state
;
1134 * Gets the version of a module
1136 * @param module string name of module to get version for
1138 this.getVersion = function( module
) {
1139 if ( module
in registry
&& 'version' in registry
[module
] ) {
1140 return formatVersionNumber( registry
[module
].version
);
1146 * @deprecated use mw.loader.getVersion() instead
1148 this.version = function() {
1149 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1153 * Gets the state of a module
1155 * @param module string name of module to get state for
1157 this.getState = function( module
) {
1158 if ( module
in registry
&& 'state' in registry
[module
] ) {
1159 return registry
[module
].state
;
1165 * Get names of all registered modules.
1169 this.getModuleNames = function() {
1170 var names
= $.map( registry
, function( i
, key
) {
1176 /* Cache document ready status */
1178 $(document
).ready( function() { ready
= true; } );
1181 /** HTML construction helper functions */
1182 this.html
= new ( function () {
1183 var escapeCallback = function( s
) {
1199 * Escape a string for HTML. Converts special characters to HTML entities.
1200 * @param s The string to escape
1202 this.escape = function( s
) {
1203 return s
.replace( /['"<>&]/g, escapeCallback
);
1207 * Wrapper object for raw HTML passed to mw.html.element().
1209 this.Raw = function( value
) {
1214 * Wrapper object for CDATA element contents passed to mw.html.element()
1216 this.Cdata = function( value
) {
1221 * Create an HTML element string, with safe escaping.
1223 * @param name The tag name.
1224 * @param attrs An object with members mapping element names to values
1225 * @param contents The contents of the element. May be either:
1226 * - string: The string is escaped.
1227 * - null or undefined: The short closing form is used, e.g. <br/>.
1228 * - this.Raw: The value attribute is included without escaping.
1229 * - this.Cdata: The value attribute is included, and an exception is
1230 * thrown if it contains an illegal ETAGO delimiter.
1231 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1235 * return h.element( 'div', {},
1236 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1237 * Returns <div><img src="<"/></div>
1239 this.element = function( name
, attrs
, contents
) {
1241 for ( var attrName
in attrs
) {
1242 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1244 if ( contents
=== undefined || contents
=== null ) {
1251 if ( typeof contents
=== 'string' ) {
1253 s
+= this.escape( contents
);
1254 } else if ( contents
instanceof this.Raw
) {
1255 // Raw HTML inclusion
1256 s
+= contents
.value
;
1257 } else if ( contents
instanceof this.Cdata
) {
1259 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1260 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1262 s
+= contents
.value
;
1264 throw new Error( 'mw.html.element: Invalid type of contents' );
1266 s
+= '</' + name
+ '>';
1271 /* Extension points */
1277 // Alias $j to jQuery for backwards compatibility
1280 // Auto-register from pre-loaded startup scripts
1281 if ( typeof startUp
!== 'undefined' && jQuery
.isFunction( startUp
) ) {