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 parser
= parser
|| mw
.jqueryMsg
.getMessageFunction( );
129 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
133 Message
.prototype = {
135 * Appends (does not replace) parameters for replacement to the .parameters property.
137 * @param parameters Array
140 params: function ( parameters
) {
142 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
143 this.parameters
.push( parameters
[i
] );
149 * Converts message object to it's string form based on the state of format.
151 * @return string Message as a string in the current form or <key> if key does not exist.
153 toString: function() {
154 if ( !this.exists( ) ) {
155 // Use <key> as text if key does not exist
156 if ( this.format
!== 'plain' ) {
157 // format 'escape' and 'parse' need to have the brackets and key html escaped
158 return mw
.html
.escape( '<' + this.key
+ '>' );
160 return '<' + this.key
+ '>';
162 var text
= this.map
.get( this.key
),
163 parameters
= this.parameters
;
165 if ( this.format
=== 'plain' ) {
166 // Do not use parser unless required.
167 if ( text
.indexOf( '{{' ) < 0 ) {
168 text
= text
.replace( /\$(\d+)/g, function ( str
, match
) {
169 var index
= parseInt( match
, 10 ) - 1;
170 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
174 text
= parser( this.key
, this.parameters
);
178 if ( this.format
=== 'escaped' ) {
179 text
= parser( this.key
, this.parameters
);
180 text
= mw
.html
.escape( text
);
183 if ( this.format
=== 'parse' ) {
184 text
= parser( this.key
, this.parameters
);
191 * Changes format to parse and converts message to string
193 * @return {string} String form of parsed message
196 this.format
= 'parse';
197 return this.toString();
201 * Changes format to plain and converts message to string
203 * @return {string} String form of plain message
206 this.format
= 'plain';
207 return this.toString();
211 * Changes the format to html escaped and converts message to string
213 * @return {string} String form of html escaped message
215 escaped: function() {
216 this.format
= 'escaped';
217 return this.toString();
221 * Checks if message exists
223 * @return {string} String form of parsed message
226 return this.map
.exists( this.key
);
234 * Dummy function which in debug mode can be replaced with a function that
235 * emulates console.log in console-less environments.
240 * @var constructor Make the Map constructor publicly available.
245 * List of configuration values
247 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
248 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
249 * in the global window object.
256 * Empty object that plugins can be installed in.
260 /* Extension points */
265 * Localization system
272 * Gets a message object, similar to wfMessage()
274 * @param key string Key of message to get
275 * @param parameter_1 mixed First argument in a list of variadic arguments,
276 * each a parameter for $N replacement in messages.
279 message: function ( key
, parameter_1
/* [, parameter_2] */ ) {
281 // Support variadic arguments
282 if ( parameter_1
!== undefined ) {
283 parameters
= $.makeArray( arguments
);
288 return new Message( mw
.messages
, key
, parameters
);
292 * Gets a message string, similar to wfMsg()
294 * @param key string Key of message to get
295 * @param parameters mixed First argument in a list of variadic arguments,
296 * each a parameter for $N replacement in messages.
299 msg: function ( key
, parameters
) {
300 return mw
.message
.apply( mw
.message
, arguments
).toString();
304 * Client-side module loader which integrates with the MediaWiki ResourceLoader
306 loader
: ( function() {
308 /* Private Members */
311 * Mapping of registered modules
313 * The jquery module is pre-registered, because it must have already
314 * been provided for this object to have been built, and in debug mode
315 * jquery would have been provided through a unique loader request,
316 * making it impossible to hold back registration of jquery until after
319 * For exact details on support for script, style and messages, look at
320 * mw.loader.implement.
325 * 'version': ############## (unix timestamp),
326 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
327 * 'group': 'somegroup', (or) null,
328 * 'source': 'local', 'someforeignwiki', (or) null
329 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
332 * 'messages': { 'key': 'value' },
338 * Mapping of sources, keyed by source-id, values are objects.
342 * 'loadScript': 'http://foo.bar/w/load.php'
347 // List of modules which will be loaded as when ready
349 // List of modules to be loaded
351 // List of callback functions waiting for modules to be ready to be called
353 // Flag indicating that document ready has occured
355 // Whether we should try to load scripts in a blocking way
356 // Set with setBlocking()
358 // Selector cache for the marker element. Use getMarker() to get/use the marker!
361 /* Cache document ready status */
363 $(document
).ready( function () {
367 /* Private methods */
369 function getMarker(){
374 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
375 if ( $marker
.length
) {
378 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
379 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
384 function compare( a
, b
) {
386 if ( a
.length
!== b
.length
) {
389 for ( i
= 0; i
< b
.length
; i
+= 1 ) {
390 if ( $.isArray( a
[i
] ) ) {
391 if ( !compare( a
[i
], b
[i
] ) ) {
395 if ( a
[i
] !== b
[i
] ) {
403 * Generates an ISO8601 "basic" string from a UNIX timestamp
405 function formatVersionNumber( timestamp
) {
406 var pad = function ( a
, b
, c
) {
407 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
410 d
.setTime( timestamp
* 1000 );
412 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
413 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
418 * Recursively resolves dependencies and detects circular references
420 function recurse( module
, resolved
, unresolved
) {
423 if ( registry
[module
] === undefined ) {
424 throw new Error( 'Unknown dependency: ' + module
);
426 // Resolves dynamic loader function and replaces it with its own results
427 if ( $.isFunction( registry
[module
].dependencies
) ) {
428 registry
[module
].dependencies
= registry
[module
].dependencies();
429 // Ensures the module's dependencies are always in an array
430 if ( typeof registry
[module
].dependencies
!== 'object' ) {
431 registry
[module
].dependencies
= [registry
[module
].dependencies
];
434 // Tracks down dependencies
435 deps
= registry
[module
].dependencies
;
437 for ( n
= 0; n
< len
; n
+= 1 ) {
438 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
439 if ( $.inArray( deps
[n
], unresolved
) !== -1 ) {
441 'Circular reference detected: ' + module
+
447 unresolved
[unresolved
.length
] = module
;
448 recurse( deps
[n
], resolved
, unresolved
);
449 // module is at the end of unresolved
453 resolved
[resolved
.length
] = module
;
457 * Gets a list of module names that a module depends on in their proper dependency order
459 * @param module string module name or array of string module names
460 * @return list of dependencies, including 'module'.
461 * @throws Error if circular reference is detected
463 function resolve( module
) {
464 var modules
, m
, deps
, n
, resolved
;
466 // Allow calling with an array of module names
467 if ( $.isArray( module
) ) {
469 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
470 deps
= resolve( module
[m
] );
471 for ( n
= 0; n
< deps
.length
; n
+= 1 ) {
472 modules
[modules
.length
] = deps
[n
];
476 } else if ( typeof module
=== 'string' ) {
478 recurse( module
, resolved
, [] );
481 throw new Error( 'Invalid module argument: ' + module
);
485 * Narrows a list of module names down to those matching a specific
486 * state (see comment on top of this scope for a list of valid states).
487 * One can also filter for 'unregistered', which will return the
488 * modules names that don't have a registry entry.
490 * @param states string or array of strings of module states to filter by
491 * @param modules array list of module names to filter (optional, by default the entire
493 * @return array list of filtered module names
495 function filter( states
, modules
) {
496 var list
, module
, s
, m
;
498 // Allow states to be given as a string
499 if ( typeof states
=== 'string' ) {
502 // If called without a list of modules, build and use a list of all modules
504 if ( modules
=== undefined ) {
506 for ( module
in registry
) {
507 modules
[modules
.length
] = module
;
510 // Build a list of modules which are in one of the specified states
511 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
512 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
513 if ( registry
[modules
[m
]] === undefined ) {
514 // Module does not exist
515 if ( states
[s
] === 'unregistered' ) {
517 list
[list
.length
] = modules
[m
];
520 // Module exists, check state
521 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
523 list
[list
.length
] = modules
[m
];
532 * Automatically executes jobs and modules which are pending with satistifed dependencies.
534 * This is used when dependencies are satisfied, such as when a module is executed.
536 function handlePending( module
) {
540 // Run jobs who's dependencies have just been met
541 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
543 filter( 'ready', jobs
[j
].dependencies
),
544 jobs
[j
].dependencies
) )
546 if ( $.isFunction( jobs
[j
].ready
) ) {
553 // Execute modules who's dependencies have just been met
554 for ( r
in registry
) {
555 if ( registry
[r
].state
=== 'loaded' ) {
557 filter( ['ready'], registry
[r
].dependencies
),
558 registry
[r
].dependencies
) )
565 // Run error callbacks of jobs affected by this condition
566 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
567 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
568 if ( $.isFunction( jobs
[j
].error
) ) {
569 jobs
[j
].error( e
, module
);
579 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
580 * depending on whether document-ready has occured yet and whether we are in blocking mode.
582 * @param src String: URL to script, will be used as the src attribute in the script tag
583 * @param callback Function: Optional callback which will be run when the script is done
585 function addScript( src
, callback
) {
586 var done
= false, script
, head
;
587 if ( ready
|| !blocking
) {
588 // jQuery's getScript method is NOT better than doing this the old-fashioned way
589 // because jQuery will eval the script's code, and errors will not have sane
591 script
= document
.createElement( 'script' );
592 script
.setAttribute( 'src', src
);
593 script
.setAttribute( 'type', 'text/javascript' );
594 if ( $.isFunction( callback
) ) {
595 // Attach handlers for all browsers (based on jQuery.ajax)
596 script
.onload
= script
.onreadystatechange = function() {
602 || /loaded|complete/.test( script
.readyState
)
608 // Handle memory leak in IE
609 script
.onload
= script
.onreadystatechange
= null;
613 if ( script
.parentNode
) {
614 script
.parentNode
.removeChild( script
);
617 // Dereference the script
622 // IE-safe way of getting the <head> . document.documentElement.head doesn't
623 // work in scripts that run in the <head>
624 head
= document
.getElementsByTagName( 'head' )[0];
625 // Append to the <body> if available, to the <head> otherwise
626 (document
.body
|| head
).appendChild( script
);
628 document
.write( mw
.html
.element(
629 'script', { 'type': 'text/javascript', 'src': src
}, ''
631 if ( $.isFunction( callback
) ) {
632 // Document.write is synchronous, so this is called when it's done
633 // FIXME: that's a lie. doc.write isn't actually synchronous
640 * Executes a loaded module, making it ready to use
642 * @param module string module name to execute
644 function execute( module
, callback
) {
645 var style
, media
, i
, script
, markModuleReady
, nestedAddScript
;
647 if ( registry
[module
] === undefined ) {
648 throw new Error( 'Module has not been registered yet: ' + module
);
649 } else if ( registry
[module
].state
=== 'registered' ) {
650 throw new Error( 'Module has not been requested from the server yet: ' + module
);
651 } else if ( registry
[module
].state
=== 'loading' ) {
652 throw new Error( 'Module has not completed loading yet: ' + module
);
653 } else if ( registry
[module
].state
=== 'ready' ) {
654 throw new Error( 'Module has already been loaded: ' + module
);
658 if ( $.isPlainObject( registry
[module
].style
) ) {
659 for ( media
in registry
[module
].style
) {
660 style
= registry
[module
].style
[media
];
661 if ( $.isArray( style
) ) {
662 for ( i
= 0; i
< style
.length
; i
+= 1 ) {
663 getMarker().before( mw
.html
.element( 'link', {
670 } else if ( typeof style
=== 'string' ) {
671 getMarker().before( mw
.html
.element( 'style', {
674 }, new mw
.html
.Cdata( style
) ) );
678 // Add localizations to message system
679 if ( $.isPlainObject( registry
[module
].messages
) ) {
680 mw
.messages
.set( registry
[module
].messages
);
684 script
= registry
[module
].script
;
685 markModuleReady = function() {
686 registry
[module
].state
= 'ready';
687 handlePending( module
);
688 if ( $.isFunction( callback
) ) {
692 nestedAddScript = function ( arr
, callback
, i
) {
693 // Recursively call addScript() in its own callback
694 // for each element of arr.
695 if ( i
>= arr
.length
) {
696 // We're at the end of the array
701 addScript( arr
[i
], function() {
702 nestedAddScript( arr
, callback
, i
+ 1 );
706 if ( $.isArray( script
) ) {
707 registry
[module
].state
= 'loading';
708 nestedAddScript( script
, markModuleReady
, 0 );
709 } else if ( $.isFunction( script
) ) {
714 // This needs to NOT use mw.log because these errors are common in production mode
715 // and not in debug mode, such as when a symbol that should be global isn't exported
716 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
717 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
719 registry
[module
].state
= 'error';
725 * Adds a dependencies to the queue with optional callbacks to be run
726 * when the dependencies are ready or fail
728 * @param dependencies string module name or array of string module names
729 * @param ready function callback to execute when all dependencies are ready
730 * @param error function callback to execute when any dependency fails
732 function request( dependencies
, ready
, error
) {
733 var regItemDeps
, regItemDepLen
, n
;
735 // Allow calling by single module name
736 if ( typeof dependencies
=== 'string' ) {
737 dependencies
= [dependencies
];
738 if ( registry
[dependencies
[0]] !== undefined ) {
739 // Cache repetitively accessed deep level object member
740 regItemDeps
= registry
[dependencies
[0]].dependencies
;
741 // Cache to avoid looped access to length property
742 regItemDepLen
= regItemDeps
.length
;
743 for ( n
= 0; n
< regItemDepLen
; n
+= 1 ) {
744 dependencies
[dependencies
.length
] = regItemDeps
[n
];
748 // Add ready and error callbacks if they were given
749 if ( arguments
.length
> 1 ) {
750 jobs
[jobs
.length
] = {
751 'dependencies': filter(
752 ['registered', 'loading', 'loaded'],
759 // Queue up any dependencies that are registered
760 dependencies
= filter( ['registered'], dependencies
);
761 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
762 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
763 queue
[queue
.length
] = dependencies
[n
];
770 function sortQuery(o
) {
771 var sorted
= {}, key
, a
= [];
773 if ( hasOwn
.call( o
, key
) ) {
778 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
779 sorted
[a
[key
]] = o
[a
[key
]];
785 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
786 * to a query string of the form foo.bar,baz|bar.baz,quux
788 function buildModulesString( moduleMap
) {
789 var arr
= [], p
, prefix
;
790 for ( prefix
in moduleMap
) {
791 p
= prefix
=== '' ? '' : prefix
+ '.';
792 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
794 return arr
.join( '|' );
798 * Asynchronously append a script tag to the end of the body
799 * that invokes load.php
800 * @param moduleMap {Object}: Module map, see buildModulesString()
801 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
802 * @param sourceLoadScript {String}: URL of load.php
804 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
805 var request
= $.extend(
806 { 'modules': buildModulesString( moduleMap
) },
809 request
= sortQuery( request
);
810 // Asynchronously append a script tag to the end of the body
811 // Append &* to avoid triggering the IE6 extension check
812 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*' );
818 * Requests dependencies from server, loading and executing when things when ready.
821 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
822 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
823 currReqBase
, currReqBaseLength
, moduleMap
, l
,
824 lastDotIndex
, prefix
, suffix
, bytesAdded
;
826 // Build a list of request parameters common to all requests.
828 skin
: mw
.config
.get( 'skin' ),
829 lang
: mw
.config
.get( 'wgUserLanguage' ),
830 debug
: mw
.config
.get( 'debug' )
832 // Split module batch by source and by group.
834 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
836 // Appends a list of modules from the queue to the batch
837 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
838 // Only request modules which are registered
839 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
840 // Prevent duplicate entries
841 if ( $.inArray( queue
[q
], batch
) === -1 ) {
842 batch
[batch
.length
] = queue
[q
];
843 // Mark registered modules as loading
844 registry
[queue
[q
]].state
= 'loading';
848 // Early exit if there's nothing to load...
849 if ( !batch
.length
) {
853 // The queue has been processed into the batch, clear up the queue.
856 // Always order modules alphabetically to help reduce cache
857 // misses for otherwise identical content.
860 // Split batch by source and by group.
861 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
862 bSource
= registry
[batch
[b
]].source
;
863 bGroup
= registry
[batch
[b
]].group
;
864 if ( splits
[bSource
] === undefined ) {
865 splits
[bSource
] = {};
867 if ( splits
[bSource
][bGroup
] === undefined ) {
868 splits
[bSource
][bGroup
] = [];
870 bSourceGroup
= splits
[bSource
][bGroup
];
871 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
874 // Clear the batch - this MUST happen before we append any
875 // script elements to the body or it's possible that a script
876 // will be locally cached, instantly load, and work the batch
877 // again, all before we've cleared it causing each request to
878 // include modules which are already loaded.
881 for ( source
in splits
) {
883 sourceLoadScript
= sources
[source
].loadScript
;
885 for ( group
in splits
[source
] ) {
887 // Cache access to currently selected list of
888 // modules for this group from this source.
889 modules
= splits
[source
][group
];
891 // Calculate the highest timestamp
893 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
894 if ( registry
[modules
[g
]].version
> maxVersion
) {
895 maxVersion
= registry
[modules
[g
]].version
;
899 currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
);
900 currReqBaseLength
= $.param( currReqBase
).length
;
902 // We may need to split up the request to honor the query string length limit,
903 // so build it piece by piece.
904 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
906 moduleMap
= {}; // { prefix: [ suffixes ] }
908 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
909 // Determine how many bytes this module would add to the query string
910 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
911 // Note that these substr() calls work even if lastDotIndex == -1
912 prefix
= modules
[i
].substr( 0, lastDotIndex
);
913 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
914 bytesAdded
= moduleMap
[prefix
] !== undefined
915 ? suffix
.length
+ 3 // '%2C'.length == 3
916 : modules
[i
].length
+ 3; // '%7C'.length == 3
918 // If the request would become too long, create a new one,
919 // but don't create empty requests
920 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
921 // This request would become too long, create a new one
922 // and fire off the old one
923 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
925 l
= currReqBaseLength
+ 9;
927 if ( moduleMap
[prefix
] === undefined ) {
928 moduleMap
[prefix
] = [];
930 moduleMap
[prefix
].push( suffix
);
933 // If there's anything left in moduleMap, request that too
934 if ( !$.isEmptyObject( moduleMap
) ) {
935 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
944 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
945 * @param props {Object}: Object containing only the loadScript property which is a url to
946 * the load.php location of the source.
949 addSource: function ( id
, props
) {
951 // Allow multiple additions
952 if ( typeof id
=== 'object' ) {
953 for ( source
in id
) {
954 mw
.loader
.addSource( source
, id
[source
] );
959 if ( sources
[id
] !== undefined ) {
960 throw new Error( 'source already registered: ' + id
);
969 * Registers a module, letting the system know about it and its
970 * properties. Startup modules contain calls to this function.
972 * @param module {String}: Module name
973 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
974 * @param dependencies {String|Array|Function}: One string or array of strings of module
975 * names on which this module depends, or a function that returns that array.
976 * @param group {String}: Group which the module is in (optional, defaults to null)
977 * @param source {String}: Name of the source. Defaults to local.
979 register: function ( module
, version
, dependencies
, group
, source
) {
981 // Allow multiple registration
982 if ( typeof module
=== 'object' ) {
983 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
984 // module is an array of module names
985 if ( typeof module
[m
] === 'string' ) {
986 mw
.loader
.register( module
[m
] );
987 // module is an array of arrays
988 } else if ( typeof module
[m
] === 'object' ) {
989 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
995 if ( typeof module
!== 'string' ) {
996 throw new Error( 'module must be a string, not a ' + typeof module
);
998 if ( registry
[module
] !== undefined ) {
999 throw new Error( 'module already registered: ' + module
);
1001 // List the module as registered
1002 registry
[module
] = {
1003 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
1005 'group': typeof group
=== 'string' ? group
: null,
1006 'source': typeof source
=== 'string' ? source
: 'local',
1007 'state': 'registered'
1009 if ( typeof dependencies
=== 'string' ) {
1010 // Allow dependencies to be given as a single module name
1011 registry
[module
].dependencies
= [dependencies
];
1012 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1013 // Allow dependencies to be given as an array of module names
1014 // or a function which returns an array
1015 registry
[module
].dependencies
= dependencies
;
1020 * Implements a module, giving the system a course of action to take
1021 * upon loading. Results of a request for one or more modules contain
1022 * calls to this function.
1024 * All arguments are required.
1026 * @param module String: Name of module
1027 * @param script Mixed: Function of module code or String of URL to be used as the src
1028 * attribute when adding a script element to the body
1029 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1030 * keyed by media-type
1031 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1033 implement: function ( module
, script
, style
, msgs
) {
1035 if ( typeof module
!== 'string' ) {
1036 throw new Error( 'module must be a string, not a ' + typeof module
);
1038 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1039 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1041 if ( !$.isPlainObject( style
) ) {
1042 throw new Error( 'style must be an object, not a ' + typeof style
);
1044 if ( !$.isPlainObject( msgs
) ) {
1045 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1047 // Automatically register module
1048 if ( registry
[module
] === undefined ) {
1049 mw
.loader
.register( module
);
1051 // Check for duplicate implementation
1052 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1053 throw new Error( 'module already implemented: ' + module
);
1055 // Mark module as loaded
1056 registry
[module
].state
= 'loaded';
1057 // Attach components
1058 registry
[module
].script
= script
;
1059 registry
[module
].style
= style
;
1060 registry
[module
].messages
= msgs
;
1061 // Execute or queue callback
1063 filter( ['ready'], registry
[module
].dependencies
),
1064 registry
[module
].dependencies
) )
1071 * Executes a function as soon as one or more required modules are ready
1073 * @param dependencies {String|Array} Module name or array of modules names the callback
1074 * dependends on to be ready before executing
1075 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1076 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1078 using: function ( dependencies
, ready
, error
) {
1079 var tod
= typeof dependencies
;
1081 if ( tod
!== 'object' && tod
!== 'string' ) {
1082 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1084 // Allow calling with a single dependency as a string
1085 if ( tod
=== 'string' ) {
1086 dependencies
= [dependencies
];
1088 // Resolve entire dependency map
1089 dependencies
= resolve( dependencies
);
1090 // If all dependencies are met, execute ready immediately
1091 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1092 if ( $.isFunction( ready
) ) {
1096 // If any dependencies have errors execute error immediately
1097 else if ( filter( ['error'], dependencies
).length
) {
1098 if ( $.isFunction( error
) ) {
1099 error( new Error( 'one or more dependencies have state "error"' ),
1103 // Since some dependencies are not yet ready, queue up a request
1105 request( dependencies
, ready
, error
);
1110 * Loads an external script or one or more modules for future use
1112 * @param modules {mixed} Either the name of a module, array of modules,
1113 * or a URL of an external script or style
1114 * @param type {String} mime-type to use if calling with a URL of an
1115 * external script or style; acceptable values are "text/css" and
1116 * "text/javascript"; if no type is provided, text/javascript is assumed.
1118 load: function ( modules
, type
) {
1122 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1123 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1125 // Allow calling with an external url or single dependency as a string
1126 if ( typeof modules
=== 'string' ) {
1127 // Support adding arbitrary external scripts
1128 if ( /^(https?:)?\/\//.test( modules
) ) {
1129 if ( type
=== 'text/css' ) {
1130 $( 'head' ).append( $( '<link>', {
1136 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
1137 addScript( modules
);
1141 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1143 // Called with single module
1144 modules
= [modules
];
1147 // Filter out undefined modules, otherwise resolve() will throw
1148 // an exception for trying to load an undefined module.
1149 // Undefined modules are acceptable here in load(), because load() takes
1150 // an array of unrelated modules, whereas the modules passed to
1151 // using() are related and must all be loaded.
1152 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1153 if ( registry
[modules
[m
]] !== undefined ) {
1154 filtered
[filtered
.length
] = modules
[m
];
1158 // Resolve entire dependency map
1159 filtered
= resolve( filtered
);
1160 // If all modules are ready, nothing dependency be done
1161 if ( compare( filter( ['ready'], filtered
), filtered
) ) {
1164 // If any modules have errors
1165 else if ( filter( ['error'], filtered
).length
) {
1168 // Since some modules are not yet ready, queue up a request
1170 request( filtered
);
1176 * Changes the state of a module
1178 * @param module {String|Object} module name or object of module name/state pairs
1179 * @param state {String} state name
1181 state: function ( module
, state
) {
1183 if ( typeof module
=== 'object' ) {
1184 for ( m
in module
) {
1185 mw
.loader
.state( m
, module
[m
] );
1189 if ( registry
[module
] === undefined ) {
1190 mw
.loader
.register( module
);
1192 registry
[module
].state
= state
;
1196 * Gets the version of a module
1198 * @param module string name of module to get version for
1200 getVersion: function ( module
) {
1201 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1202 return formatVersionNumber( registry
[module
].version
);
1208 * @deprecated since 1.18 use mw.loader.getVersion() instead
1210 version: function () {
1211 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1215 * Gets the state of a module
1217 * @param module string name of module to get state for
1219 getState: function ( module
) {
1220 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1221 return registry
[module
].state
;
1227 * Get names of all registered modules.
1231 getModuleNames: function () {
1232 return $.map( registry
, function ( i
, key
) {
1238 * Enable or disable blocking. If blocking is enabled and
1239 * document ready has not yet occurred, scripts will be loaded
1240 * in a blocking way (using document.write) rather than
1241 * asynchronously using DOM manipulation
1243 * @param b {Boolean} True to enable blocking, false to disable it
1245 setBlocking: function( b
) {
1250 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1253 mw
.loader
.load( 'mediawiki.user' );
1258 /** HTML construction helper functions */
1259 html
: ( function () {
1260 function escapeCallback( s
) {
1277 * Escape a string for HTML. Converts special characters to HTML entities.
1278 * @param s The string to escape
1280 escape: function ( s
) {
1281 return s
.replace( /['"<>&]/g, escapeCallback
);
1285 * Wrapper object for raw HTML passed to mw.html.element().
1288 Raw: function ( value
) {
1293 * Wrapper object for CDATA element contents passed to mw.html.element()
1296 Cdata: function ( value
) {
1301 * Create an HTML element string, with safe escaping.
1303 * @param name The tag name.
1304 * @param attrs An object with members mapping element names to values
1305 * @param contents The contents of the element. May be either:
1306 * - string: The string is escaped.
1307 * - null or undefined: The short closing form is used, e.g. <br/>.
1308 * - this.Raw: The value attribute is included without escaping.
1309 * - this.Cdata: The value attribute is included, and an exception is
1310 * thrown if it contains an illegal ETAGO delimiter.
1311 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1315 * return h.element( 'div', {},
1316 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1317 * Returns <div><img src="<"/></div>
1319 element: function ( name
, attrs
, contents
) {
1320 var v
, attrName
, s
= '<' + name
;
1322 for ( attrName
in attrs
) {
1323 v
= attrs
[attrName
];
1324 // Convert name=true, to name=name
1328 } else if ( v
=== false ) {
1331 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1333 if ( contents
=== undefined || contents
=== null ) {
1340 switch ( typeof contents
) {
1343 s
+= this.escape( contents
);
1347 // Convert to string
1348 s
+= String( contents
);
1351 if ( contents
instanceof this.Raw
) {
1352 // Raw HTML inclusion
1353 s
+= contents
.value
;
1354 } else if ( contents
instanceof this.Cdata
) {
1356 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1357 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1359 s
+= contents
.value
;
1361 throw new Error( 'mw.html.element: Invalid type of contents' );
1364 s
+= '</' + name
+ '>';
1373 // Alias $j to jQuery for backwards compatibility
1376 // Attach to window and globally alias
1377 window
.mw
= window
.mediaWiki
= mw
;
1379 // Auto-register from pre-loaded startup scripts
1380 if ( typeof startUp
!== 'undefined' && jQuery
.isFunction( startUp
) ) {
1382 startUp
= undefined;