2 * Core MediaWiki JavaScript Library
5 var mw
= ( function ( $, undefined ) {
10 var hasOwn
= Object
.prototype.hasOwnProperty
;
12 /* Object constructors */
17 * Creates an object that can be read from or written to from prototype functions
18 * that allow both single and multiple variables at once.
20 * @param global boolean Whether to store the values in the global window
21 * object or a exclusively in the object property 'values'.
24 function Map( global
) {
25 this.values
= global
=== true ? window
: {};
31 * Get the value of one or multiple a keys.
33 * If called with no arguments, all values will be returned.
35 * @param selection mixed String key or array of keys to get values for.
36 * @param fallback mixed Value to use in case key(s) do not exist (optional).
37 * @return mixed If selection was a string returns the value or null,
38 * If selection was an array, returns an object of key/values (value is null if not found),
39 * If selection was not passed or invalid, will return the 'values' object member (be careful as
40 * objects are always passed by reference in JavaScript!).
41 * @return Values as a string or object, null if invalid/inexistant.
43 get: function ( selection
, fallback
) {
46 if ( $.isArray( selection
) ) {
47 selection
= $.makeArray( selection
);
49 for ( i
= 0; i
< selection
.length
; i
+= 1 ) {
50 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
53 } else if ( typeof selection
=== 'string' ) {
54 if ( this.values
[selection
] === undefined ) {
55 if ( fallback
!== undefined ) {
60 return this.values
[selection
];
62 if ( selection
=== undefined ) {
65 return null; // invalid selection key
70 * Sets one or multiple key/value pairs.
72 * @param selection {mixed} String key or array of keys to set values for.
73 * @param value {mixed} Value to set (optional, only in use when key is a string)
74 * @return {Boolean} This returns true on success, false on failure.
76 set: function ( selection
, value
) {
79 if ( $.isPlainObject( selection
) ) {
80 for ( s
in selection
) {
81 this.values
[s
] = selection
[s
];
84 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
85 this.values
[selection
] = value
;
92 * Checks if one or multiple keys exist.
94 * @param selection {mixed} String key or array of keys to check
95 * @return {Boolean} Existence of key(s)
97 exists: function ( selection
) {
100 if ( $.isArray( selection
) ) {
101 for ( s
= 0; s
< selection
.length
; s
+= 1 ) {
102 if ( this.values
[selection
[s
]] === undefined ) {
108 return this.values
[selection
] !== undefined;
116 * Object constructor for messages,
117 * similar to the Message class in MediaWiki PHP.
119 * @param map Map Instance of mw.Map
121 * @param parameters Array
124 function Message( map
, key
, parameters
) {
125 this.format
= 'plain';
128 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
132 Message
.prototype = {
134 * Appends (does not replace) parameters for replacement to the .parameters property.
136 * @param parameters Array
139 params: function ( parameters
) {
141 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
142 this.parameters
.push( parameters
[i
] );
148 * Converts message object to it's string form based on the state of format.
150 * @return string Message as a string in the current form or <key> if key does not exist.
152 toString: function() {
153 if ( !this.map
.exists( this.key
) ) {
154 // Use <key> as text if key does not exist
155 if ( this.format
!== 'plain' ) {
156 // format 'escape' and 'parse' need to have the brackets and key html escaped
157 return mw
.html
.escape( '<' + this.key
+ '>' );
159 return '<' + this.key
+ '>';
161 var text
= this.map
.get( this.key
),
162 parameters
= this.parameters
;
164 text
= text
.replace( /\$(\d+)/g, function ( str
, match
) {
165 var index
= parseInt( match
, 10 ) - 1;
166 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
169 if ( this.format
=== 'plain' ) {
172 if ( this.format
=== 'escaped' ) {
173 // According to Message.php this needs {{-transformation, which is
175 return mw
.html
.escape( text
);
178 /* This should be fixed up when we have a parser
179 if ( this.format === 'parse' && 'language' in mw ) {
180 text = mw.language.parse( text );
187 * Changes format to parse and converts message to string
189 * @return {string} String form of parsed message
192 this.format
= 'parse';
193 return this.toString();
197 * Changes format to plain and converts message to string
199 * @return {string} String form of plain message
202 this.format
= 'plain';
203 return this.toString();
207 * Changes the format to html escaped and converts message to string
209 * @return {string} String form of html escaped message
211 escaped: function() {
212 this.format
= 'escaped';
213 return this.toString();
217 * Checks if message exists
219 * @return {string} String form of parsed message
222 return this.map
.exists( this.key
);
230 * Dummy function which in debug mode can be replaced with a function that
231 * emulates console.log in console-less environments.
236 * @var constructor Make the Map constructor publicly available.
241 * List of configuration values
243 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
244 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
245 * in the global window object.
252 * Empty object that plugins can be installed in.
256 /* Extension points */
261 * Localization system
268 * Gets a message object, similar to wfMessage()
270 * @param key string Key of message to get
271 * @param parameter_1 mixed First argument in a list of variadic arguments,
272 * each a parameter for $N replacement in messages.
275 message: function ( key
, parameter_1
/* [, parameter_2] */ ) {
277 // Support variadic arguments
278 if ( parameter_1
!== undefined ) {
279 parameters
= $.makeArray( arguments
);
284 return new Message( mw
.messages
, key
, parameters
);
288 * Gets a message string, similar to wfMsg()
290 * @param key string Key of message to get
291 * @param parameters mixed First argument in a list of variadic arguments,
292 * each a parameter for $N replacement in messages.
295 msg: function ( key
, parameters
) {
296 return mw
.message
.apply( mw
.message
, arguments
).toString();
300 * Client-side module loader which integrates with the MediaWiki ResourceLoader
302 loader
: ( function() {
304 /* Private Members */
307 * Mapping of registered modules
309 * The jquery module is pre-registered, because it must have already
310 * been provided for this object to have been built, and in debug mode
311 * jquery would have been provided through a unique loader request,
312 * making it impossible to hold back registration of jquery until after
315 * For exact details on support for script, style and messages, look at
316 * mw.loader.implement.
321 * 'version': ############## (unix timestamp),
322 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
323 * 'group': 'somegroup', (or) null,
324 * 'source': 'local', 'someforeignwiki', (or) null
325 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
328 * 'messages': { 'key': 'value' },
334 * Mapping of sources, keyed by source-id, values are objects.
338 * 'loadScript': 'http://foo.bar/w/load.php'
343 // List of modules which will be loaded as when ready
345 // List of modules to be loaded
347 // List of callback functions waiting for modules to be ready to be called
349 // Flag inidicating that document ready has occured
351 // Selector cache for the marker element. Use getMarker() to get/use the marker!
354 /* Cache document ready status */
356 $(document
).ready( function () {
360 /* Private methods */
362 function getMarker(){
367 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
368 if ( $marker
.length
) {
371 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
372 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
377 function compare( a
, b
) {
379 if ( a
.length
!== b
.length
) {
382 for ( i
= 0; i
< b
.length
; i
+= 1 ) {
383 if ( $.isArray( a
[i
] ) ) {
384 if ( !compare( a
[i
], b
[i
] ) ) {
388 if ( a
[i
] !== b
[i
] ) {
396 * Generates an ISO8601 "basic" string from a UNIX timestamp
398 function formatVersionNumber( timestamp
) {
399 var pad = function ( a
, b
, c
) {
400 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
403 d
.setTime( timestamp
* 1000 );
405 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
406 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
411 * Recursively resolves dependencies and detects circular references
413 function recurse( module
, resolved
, unresolved
) {
416 if ( registry
[module
] === undefined ) {
417 throw new Error( 'Unknown dependency: ' + module
);
419 // Resolves dynamic loader function and replaces it with its own results
420 if ( $.isFunction( registry
[module
].dependencies
) ) {
421 registry
[module
].dependencies
= registry
[module
].dependencies();
422 // Ensures the module's dependencies are always in an array
423 if ( typeof registry
[module
].dependencies
!== 'object' ) {
424 registry
[module
].dependencies
= [registry
[module
].dependencies
];
427 // Tracks down dependencies
428 deps
= registry
[module
].dependencies
;
430 for ( n
= 0; n
< len
; n
+= 1 ) {
431 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
432 if ( $.inArray( deps
[n
], unresolved
) !== -1 ) {
434 'Circular reference detected: ' + module
+
438 recurse( deps
[n
], resolved
, unresolved
);
441 resolved
[resolved
.length
] = module
;
442 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
446 * Gets a list of module names that a module depends on in their proper dependency order
448 * @param module string module name or array of string module names
449 * @return list of dependencies
450 * @throws Error if circular reference is detected
452 function resolve( module
) {
453 var modules
, m
, deps
, n
, resolved
;
455 // Allow calling with an array of module names
456 if ( $.isArray( module
) ) {
458 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
459 deps
= resolve( module
[m
] );
460 for ( n
= 0; n
< deps
.length
; n
+= 1 ) {
461 modules
[modules
.length
] = deps
[n
];
465 } else if ( typeof module
=== 'string' ) {
466 // Undefined modules have no dependencies
467 if ( registry
[module
] === undefined ) {
471 recurse( module
, resolved
, [] );
474 throw new Error( 'Invalid module argument: ' + module
);
478 * Narrows a list of module names down to those matching a specific
479 * state. Possible states are 'undefined', 'registered', 'loading',
480 * 'loaded', or 'ready'
482 * @param states string or array of strings of module states to filter by
483 * @param modules array list of module names to filter (optional, all modules
484 * will be used by default)
485 * @return array list of filtered module names
487 function filter( states
, modules
) {
488 var list
, module
, s
, m
;
490 // Allow states to be given as a string
491 if ( typeof states
=== 'string' ) {
494 // If called without a list of modules, build and use a list of all modules
496 if ( modules
=== undefined ) {
498 for ( module
in registry
) {
499 modules
[modules
.length
] = module
;
502 // Build a list of modules which are in one of the specified states
503 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
504 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
505 if ( registry
[modules
[m
]] === undefined ) {
506 // Module does not exist
507 if ( states
[s
] === 'undefined' ) {
509 list
[list
.length
] = modules
[m
];
512 // Module exists, check state
513 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
515 list
[list
.length
] = modules
[m
];
524 * Automatically executes jobs and modules which are pending with satistifed dependencies.
526 * This is used when dependencies are satisfied, such as when a module is executed.
528 function handlePending( module
) {
532 // Run jobs who's dependencies have just been met
533 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
535 filter( 'ready', jobs
[j
].dependencies
),
536 jobs
[j
].dependencies
) )
538 if ( $.isFunction( jobs
[j
].ready
) ) {
545 // Execute modules who's dependencies have just been met
546 for ( r
in registry
) {
547 if ( registry
[r
].state
=== 'loaded' ) {
549 filter( ['ready'], registry
[r
].dependencies
),
550 registry
[r
].dependencies
) )
557 // Run error callbacks of jobs affected by this condition
558 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
559 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
560 if ( $.isFunction( jobs
[j
].error
) ) {
561 jobs
[j
].error( e
, module
);
571 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
572 * depending on whether document-ready has occured yet.
574 * @param src String: URL to script, will be used as the src attribute in the script tag
575 * @param callback Function: Optional callback which will be run when the script is done
577 function addScript( src
, callback
) {
578 var done
= false, script
;
580 // jQuery's getScript method is NOT better than doing this the old-fashioned way
581 // because jQuery will eval the script's code, and errors will not have sane
583 script
= document
.createElement( 'script' );
584 script
.setAttribute( 'src', src
);
585 script
.setAttribute( 'type', 'text/javascript' );
586 if ( $.isFunction( callback
) ) {
587 // Attach handlers for all browsers (based on jQuery.ajax)
588 script
.onload
= script
.onreadystatechange = function() {
594 || /loaded|complete/.test( script
.readyState
)
600 // Handle memory leak in IE
601 script
.onload
= script
.onreadystatechange
= null;
605 if ( script
.parentNode
) {
606 script
.parentNode
.removeChild( script
);
609 // Dereference the script
614 document
.body
.appendChild( script
);
616 document
.write( mw
.html
.element(
617 'script', { 'type': 'text/javascript', 'src': src
}, ''
619 if ( $.isFunction( callback
) ) {
620 // Document.write is synchronous, so this is called when it's done
627 * Executes a loaded module, making it ready to use
629 * @param module string module name to execute
631 function execute( module
, callback
) {
632 var style
, media
, i
, script
, markModuleReady
, nestedAddScript
;
634 if ( registry
[module
] === undefined ) {
635 throw new Error( 'Module has not been registered yet: ' + module
);
636 } else if ( registry
[module
].state
=== 'registered' ) {
637 throw new Error( 'Module has not been requested from the server yet: ' + module
);
638 } else if ( registry
[module
].state
=== 'loading' ) {
639 throw new Error( 'Module has not completed loading yet: ' + module
);
640 } else if ( registry
[module
].state
=== 'ready' ) {
641 throw new Error( 'Module has already been loaded: ' + module
);
645 if ( $.isPlainObject( registry
[module
].style
) ) {
646 for ( media
in registry
[module
].style
) {
647 style
= registry
[module
].style
[media
];
648 if ( $.isArray( style
) ) {
649 for ( i
= 0; i
< style
.length
; i
+= 1 ) {
650 getMarker().before( mw
.html
.element( 'link', {
657 } else if ( typeof style
=== 'string' ) {
658 getMarker().before( mw
.html
.element( 'style', {
661 }, new mw
.html
.Cdata( style
) ) );
665 // Add localizations to message system
666 if ( $.isPlainObject( registry
[module
].messages
) ) {
667 mw
.messages
.set( registry
[module
].messages
);
671 script
= registry
[module
].script
;
672 markModuleReady = function() {
673 registry
[module
].state
= 'ready';
674 handlePending( module
);
675 if ( $.isFunction( callback
) ) {
679 nestedAddScript = function ( arr
, callback
, i
) {
680 // Recursively call addScript() in its own callback
681 // for each element of arr.
682 if ( i
>= arr
.length
) {
683 // We're at the end of the array
688 addScript( arr
[i
], function() {
689 nestedAddScript( arr
, callback
, i
+ 1 );
693 if ( $.isArray( script
) ) {
694 registry
[module
].state
= 'loading';
695 nestedAddScript( script
, markModuleReady
, 0 );
696 } else if ( $.isFunction( script
) ) {
701 // This needs to NOT use mw.log because these errors are common in production mode
702 // and not in debug mode, such as when a symbol that should be global isn't exported
703 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
704 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
706 registry
[module
].state
= 'error';
712 * Adds a dependencies to the queue with optional callbacks to be run
713 * when the dependencies are ready or fail
715 * @param dependencies string module name or array of string module names
716 * @param ready function callback to execute when all dependencies are ready
717 * @param error function callback to execute when any dependency fails
719 function request( dependencies
, ready
, error
) {
720 var regItemDeps
, regItemDepLen
, n
;
722 // Allow calling by single module name
723 if ( typeof dependencies
=== 'string' ) {
724 dependencies
= [dependencies
];
725 if ( registry
[dependencies
[0]] !== undefined ) {
726 // Cache repetitively accessed deep level object member
727 regItemDeps
= registry
[dependencies
[0]].dependencies
;
728 // Cache to avoid looped access to length property
729 regItemDepLen
= regItemDeps
.length
;
730 for ( n
= 0; n
< regItemDepLen
; n
+= 1 ) {
731 dependencies
[dependencies
.length
] = regItemDeps
[n
];
735 // Add ready and error callbacks if they were given
736 if ( arguments
.length
> 1 ) {
737 jobs
[jobs
.length
] = {
738 'dependencies': filter(
739 ['undefined', 'registered', 'loading', 'loaded'],
746 // Queue up any dependencies that are undefined or registered
747 dependencies
= filter( ['undefined', 'registered'], dependencies
);
748 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
749 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
750 queue
[queue
.length
] = dependencies
[n
];
757 function sortQuery(o
) {
758 var sorted
= {}, key
, a
= [];
760 if ( hasOwn
.call( o
, key
) ) {
765 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
766 sorted
[a
[key
]] = o
[a
[key
]];
772 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
773 * to a query string of the form foo.bar,baz|bar.baz,quux
775 function buildModulesString( moduleMap
) {
776 var arr
= [], p
, prefix
;
777 for ( prefix
in moduleMap
) {
778 p
= prefix
=== '' ? '' : prefix
+ '.';
779 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
781 return arr
.join( '|' );
785 * Asynchronously append a script tag to the end of the body
786 * that invokes load.php
787 * @param moduleMap {Object}: Module map, see buildModulesString()
788 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
789 * @param sourceLoadScript {String}: URL of load.php
791 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
792 var request
= $.extend(
793 { 'modules': buildModulesString( moduleMap
) },
796 request
= sortQuery( request
);
797 // Asynchronously append a script tag to the end of the body
798 // Append &* to avoid triggering the IE6 extension check
799 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*' );
805 * Requests dependencies from server, loading and executing when things when ready.
808 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
809 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
810 currReqBase
, currReqBaseLength
, moduleMap
, l
,
811 lastDotIndex
, prefix
, suffix
, bytesAdded
;
813 // Build a list of request parameters common to all requests.
815 skin
: mw
.config
.get( 'skin' ),
816 lang
: mw
.config
.get( 'wgUserLanguage' ),
817 debug
: mw
.config
.get( 'debug' )
819 // Split module batch by source and by group.
821 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
823 // Appends a list of modules from the queue to the batch
824 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
825 // Only request modules which are undefined or registered
826 if ( registry
[queue
[q
]] === undefined || registry
[queue
[q
]].state
=== 'registered' ) {
827 // Prevent duplicate entries
828 if ( $.inArray( queue
[q
], batch
) === -1 ) {
829 batch
[batch
.length
] = queue
[q
];
830 // Mark registered modules as loading
831 if ( registry
[queue
[q
]] !== undefined ) {
832 registry
[queue
[q
]].state
= 'loading';
837 // Early exit if there's nothing to load...
838 if ( !batch
.length
) {
842 // The queue has been processed into the batch, clear up the queue.
845 // Always order modules alphabetically to help reduce cache
846 // misses for otherwise identical content.
849 // Split batch by source and by group.
850 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
851 bSource
= registry
[batch
[b
]].source
;
852 bGroup
= registry
[batch
[b
]].group
;
853 if ( splits
[bSource
] === undefined ) {
854 splits
[bSource
] = {};
856 if ( splits
[bSource
][bGroup
] === undefined ) {
857 splits
[bSource
][bGroup
] = [];
859 bSourceGroup
= splits
[bSource
][bGroup
];
860 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
863 // Clear the batch - this MUST happen before we append any
864 // script elements to the body or it's possible that a script
865 // will be locally cached, instantly load, and work the batch
866 // again, all before we've cleared it causing each request to
867 // include modules which are already loaded.
870 for ( source
in splits
) {
872 sourceLoadScript
= sources
[source
].loadScript
;
874 for ( group
in splits
[source
] ) {
876 // Cache access to currently selected list of
877 // modules for this group from this source.
878 modules
= splits
[source
][group
];
880 // Calculate the highest timestamp
882 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
883 if ( registry
[modules
[g
]].version
> maxVersion
) {
884 maxVersion
= registry
[modules
[g
]].version
;
888 currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
);
889 currReqBaseLength
= $.param( currReqBase
).length
;
891 // We may need to split up the request to honor the query string length limit,
892 // so build it piece by piece.
893 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
895 moduleMap
= {}; // { prefix: [ suffixes ] }
897 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
898 // Determine how many bytes this module would add to the query string
899 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
900 // Note that these substr() calls work even if lastDotIndex == -1
901 prefix
= modules
[i
].substr( 0, lastDotIndex
);
902 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
903 bytesAdded
= moduleMap
[prefix
] !== undefined
904 ? suffix
.length
+ 3 // '%2C'.length == 3
905 : modules
[i
].length
+ 3; // '%7C'.length == 3
907 // If the request would become too long, create a new one,
908 // but don't create empty requests
909 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
910 // This request would become too long, create a new one
911 // and fire off the old one
912 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
914 l
= currReqBaseLength
+ 9;
916 if ( moduleMap
[prefix
] === undefined ) {
917 moduleMap
[prefix
] = [];
919 moduleMap
[prefix
].push( suffix
);
922 // If there's anything left in moduleMap, request that too
923 if ( !$.isEmptyObject( moduleMap
) ) {
924 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
933 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
934 * @param props {Object}: Object containing only the loadScript property which is a url to
935 * the load.php location of the source.
938 addSource: function ( id
, props
) {
940 // Allow multiple additions
941 if ( typeof id
=== 'object' ) {
942 for ( source
in id
) {
943 mw
.loader
.addSource( source
, id
[source
] );
948 if ( sources
[id
] !== undefined ) {
949 throw new Error( 'source already registered: ' + id
);
958 * Registers a module, letting the system know about it and its
959 * properties. Startup modules contain calls to this function.
961 * @param module {String}: Module name
962 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
963 * @param dependencies {String|Array|Function}: One string or array of strings of module
964 * names on which this module depends, or a function that returns that array.
965 * @param group {String}: Group which the module is in (optional, defaults to null)
966 * @param source {String}: Name of the source. Defaults to local.
968 register: function ( module
, version
, dependencies
, group
, source
) {
970 // Allow multiple registration
971 if ( typeof module
=== 'object' ) {
972 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
973 // module is an array of module names
974 if ( typeof module
[m
] === 'string' ) {
975 mw
.loader
.register( module
[m
] );
976 // module is an array of arrays
977 } else if ( typeof module
[m
] === 'object' ) {
978 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
984 if ( typeof module
!== 'string' ) {
985 throw new Error( 'module must be a string, not a ' + typeof module
);
987 if ( registry
[module
] !== undefined ) {
988 throw new Error( 'module already implemented: ' + module
);
990 // List the module as registered
992 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
994 'group': typeof group
=== 'string' ? group
: null,
995 'source': typeof source
=== 'string' ? source
: 'local',
996 'state': 'registered'
998 if ( typeof dependencies
=== 'string' ) {
999 // Allow dependencies to be given as a single module name
1000 registry
[module
].dependencies
= [dependencies
];
1001 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1002 // Allow dependencies to be given as an array of module names
1003 // or a function which returns an array
1004 registry
[module
].dependencies
= dependencies
;
1009 * Implements a module, giving the system a course of action to take
1010 * upon loading. Results of a request for one or more modules contain
1011 * calls to this function.
1013 * All arguments are required.
1015 * @param module String: Name of module
1016 * @param script Mixed: Function of module code or String of URL to be used as the src
1017 * attribute when adding a script element to the body
1018 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1019 * keyed by media-type
1020 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1022 implement: function ( module
, script
, style
, msgs
) {
1024 if ( typeof module
!== 'string' ) {
1025 throw new Error( 'module must be a string, not a ' + typeof module
);
1027 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1028 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1030 if ( !$.isPlainObject( style
) ) {
1031 throw new Error( 'style must be an object, not a ' + typeof style
);
1033 if ( !$.isPlainObject( msgs
) ) {
1034 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1036 // Automatically register module
1037 if ( registry
[module
] === undefined ) {
1038 mw
.loader
.register( module
);
1040 // Check for duplicate implementation
1041 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1042 throw new Error( 'module already implemented: ' + module
);
1044 // Mark module as loaded
1045 registry
[module
].state
= 'loaded';
1046 // Attach components
1047 registry
[module
].script
= script
;
1048 registry
[module
].style
= style
;
1049 registry
[module
].messages
= msgs
;
1050 // Execute or queue callback
1052 filter( ['ready'], registry
[module
].dependencies
),
1053 registry
[module
].dependencies
) )
1062 * Executes a function as soon as one or more required modules are ready
1064 * @param dependencies {String|Array} Module name or array of modules names the callback
1065 * dependends on to be ready before executing
1066 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1067 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1069 using: function ( dependencies
, ready
, error
) {
1070 var tod
= typeof dependencies
;
1072 if ( tod
!== 'object' && tod
!== 'string' ) {
1073 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1075 // Allow calling with a single dependency as a string
1076 if ( tod
=== 'string' ) {
1077 dependencies
= [dependencies
];
1079 // Resolve entire dependency map
1080 dependencies
= resolve( dependencies
);
1081 // If all dependencies are met, execute ready immediately
1082 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1083 if ( $.isFunction( ready
) ) {
1087 // If any dependencies have errors execute error immediately
1088 else if ( filter( ['error'], dependencies
).length
) {
1089 if ( $.isFunction( error
) ) {
1090 error( new Error( 'one or more dependencies have state "error"' ),
1094 // Since some dependencies are not yet ready, queue up a request
1096 request( dependencies
, ready
, error
);
1101 * Loads an external script or one or more modules for future use
1103 * @param modules {mixed} Either the name of a module, array of modules,
1104 * or a URL of an external script or style
1105 * @param type {String} mime-type to use if calling with a URL of an
1106 * external script or style; acceptable values are "text/css" and
1107 * "text/javascript"; if no type is provided, text/javascript is assumed.
1109 load: function ( modules
, type
) {
1111 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1112 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1114 // Allow calling with an external script or single dependency as a string
1115 if ( typeof modules
=== 'string' ) {
1116 // Support adding arbitrary external scripts
1117 if ( /^(https?:)?\/\//.test( modules
) ) {
1118 if ( type
=== 'text/css' ) {
1119 $( 'head' ).append( $( '<link/>', {
1125 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
1126 addScript( modules
);
1132 // Called with single module
1133 modules
= [modules
];
1135 // Resolve entire dependency map
1136 modules
= resolve( modules
);
1137 // If all modules are ready, nothing dependency be done
1138 if ( compare( filter( ['ready'], modules
), modules
) ) {
1141 // If any modules have errors return false
1142 else if ( filter( ['error'], modules
).length
) {
1145 // Since some modules are not yet ready, queue up a request
1153 * Changes the state of a module
1155 * @param module {String|Object} module name or object of module name/state pairs
1156 * @param state {String} state name
1158 state: function ( module
, state
) {
1160 if ( typeof module
=== 'object' ) {
1161 for ( m
in module
) {
1162 mw
.loader
.state( m
, module
[m
] );
1166 if ( registry
[module
] === undefined ) {
1167 mw
.loader
.register( module
);
1169 registry
[module
].state
= state
;
1173 * Gets the version of a module
1175 * @param module string name of module to get version for
1177 getVersion: function ( module
) {
1178 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1179 return formatVersionNumber( registry
[module
].version
);
1185 * @deprecated since 1.18 use mw.loader.getVersion() instead
1187 version: function () {
1188 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1192 * Gets the state of a module
1194 * @param module string name of module to get state for
1196 getState: function ( module
) {
1197 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1198 return registry
[module
].state
;
1204 * Get names of all registered modules.
1208 getModuleNames: function () {
1209 return $.map( registry
, function ( i
, key
) {
1215 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1218 mw
.loader
.load( 'mediawiki.user' );
1223 /** HTML construction helper functions */
1224 html
: ( function () {
1225 function escapeCallback( s
) {
1242 * Escape a string for HTML. Converts special characters to HTML entities.
1243 * @param s The string to escape
1245 escape: function ( s
) {
1246 return s
.replace( /['"<>&]/g, escapeCallback
);
1250 * Wrapper object for raw HTML passed to mw.html.element().
1253 Raw: function ( value
) {
1258 * Wrapper object for CDATA element contents passed to mw.html.element()
1261 Cdata: function ( value
) {
1266 * Create an HTML element string, with safe escaping.
1268 * @param name The tag name.
1269 * @param attrs An object with members mapping element names to values
1270 * @param contents The contents of the element. May be either:
1271 * - string: The string is escaped.
1272 * - null or undefined: The short closing form is used, e.g. <br/>.
1273 * - this.Raw: The value attribute is included without escaping.
1274 * - this.Cdata: The value attribute is included, and an exception is
1275 * thrown if it contains an illegal ETAGO delimiter.
1276 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1280 * return h.element( 'div', {},
1281 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1282 * Returns <div><img src="<"/></div>
1284 element: function ( name
, attrs
, contents
) {
1285 var v
, attrName
, s
= '<' + name
;
1287 for ( attrName
in attrs
) {
1288 v
= attrs
[attrName
];
1289 // Convert name=true, to name=name
1293 } else if ( v
=== false ) {
1296 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1298 if ( contents
=== undefined || contents
=== null ) {
1305 switch ( typeof contents
) {
1308 s
+= this.escape( contents
);
1312 // Convert to string
1313 s
+= String( contents
);
1316 if ( contents
instanceof this.Raw
) {
1317 // Raw HTML inclusion
1318 s
+= contents
.value
;
1319 } else if ( contents
instanceof this.Cdata
) {
1321 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1322 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1324 s
+= contents
.value
;
1326 throw new Error( 'mw.html.element: Invalid type of contents' );
1329 s
+= '</' + name
+ '>';
1338 // Alias $j to jQuery for backwards compatibility
1341 // Attach to window and globally alias
1342 window
.mw
= window
.mediaWiki
= mw
;
1344 // Auto-register from pre-loaded startup scripts
1345 if ( typeof startUp
!== 'undefined' && jQuery
.isFunction( startUp
) ) {
1347 startUp
= undefined;