2 * Core MediaWiki JavaScript Library
6 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
: {};
33 * Get the value of one or multiple a keys.
35 * If called with no arguments, all values will be returned.
37 * @param selection mixed String key or array of keys to get values for.
38 * @param fallback mixed Value to use in case key(s) do not exist (optional).
39 * @return mixed If selection was a string returns the value or null,
40 * If selection was an array, returns an object of key/values (value is null if not found),
41 * If selection was not passed or invalid, will return the 'values' object member (be careful as
42 * objects are always passed by reference in JavaScript!).
45 Map
.prototype.get = function( selection
, fallback
) {
46 if ( $.isArray( selection
) ) {
47 selection
= $.makeArray( selection
);
49 for ( var i
= 0; i
< selection
.length
; i
++ ) {
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
];
66 * Sets one or multiple key/value pairs.
68 * @param selection mixed String key or array of keys to set values for.
69 * @param value mixed Value to set (optional, only in use when key is a string)
70 * @return bool This returns true on success, false on failure.
72 Map
.prototype.set = function( selection
, value
) {
73 if ( $.isPlainObject( selection
) ) {
74 for ( var s
in selection
) {
75 this.values
[s
] = selection
[s
];
78 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
79 this.values
[selection
] = value
;
86 * Checks if one or multiple keys exist.
88 * @param selection mixed String key or array of keys to check
89 * @return boolean Existence of key(s)
91 Map
.prototype.exists = function( selection
) {
92 if ( typeof selection
=== 'object' ) {
93 for ( var s
= 0; s
< selection
.length
; s
++ ) {
94 if ( !( selection
[s
] in this.values
) ) {
100 return selection
in this.values
;
107 * Object constructor for messages,
108 * similar to the Message class in MediaWiki PHP.
110 * @param map Map Instance of mw.Map
112 * @param parameters Array
115 function Message( map
, key
, parameters
) {
116 this.format
= 'parse';
119 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
124 * Appends (does not replace) parameters for replacement to the .parameters property.
126 * @param parameters Array
129 Message
.prototype.params = function( parameters
) {
130 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
131 this.parameters
.push( parameters
[i
] );
137 * Converts message object to it's string form based on the state of format.
139 * @return string Message as a string in the current form or <key> if key does not exist.
141 Message
.prototype.toString = function() {
142 if ( !this.map
.exists( this.key
) ) {
143 // Return <key> if key does not exist
144 return '<' + this.key
+ '>';
146 var text
= this.map
.get( this.key
);
147 var parameters
= this.parameters
;
148 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
149 var index
= parseInt( match
, 10 ) - 1;
150 return index
in parameters
? parameters
[index
] : '$' + match
;
153 if ( this.format
=== 'plain' ) {
156 if ( this.format
=== 'escaped' ) {
157 // According to Message.php this needs {{-transformation, which is
159 return mw
.html
.escape( text
);
162 /* This should be fixed up when we have a parser
163 if ( this.format === 'parse' && 'language' in mediaWiki ) {
164 text = mw.language.parse( text );
171 * Changes format to parse and converts message to string
173 * @return {string} String form of parsed message
175 Message
.prototype.parse = function() {
176 this.format
= 'parse';
177 return this.toString();
181 * Changes format to plain and converts message to string
183 * @return {string} String form of plain message
185 Message
.prototype.plain = function() {
186 this.format
= 'plain';
187 return this.toString();
191 * Changes the format to html escaped and converts message to string
193 * @return {string} String form of html escaped message
195 Message
.prototype.escaped = function() {
196 this.format
= 'escaped';
197 return this.toString();
201 * Checks if message exists
203 * @return {string} String form of parsed message
205 Message
.prototype.exists = function() {
206 return this.map
.exists( this.key
);
212 * Dummy function which in debug mode can be replaced with a function that
213 * emulates console.log in console-less environments.
215 this.log = function() { };
218 * @var constructor Make the Map-class publicly available.
223 * List of configuration values
225 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
226 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
227 * in the global window object.
234 * Empty object that plugins can be installed in.
239 * Localization system
241 this.messages
= new this.Map();
246 * Gets a message object, similar to wfMessage()
248 * @param key string Key of message to get
249 * @param parameter_1 mixed First argument in a list of variadic arguments,
250 * each a parameter for $N replacement in messages.
253 this.message = function( key
, parameter_1
/* [, parameter_2] */ ) {
255 // Support variadic arguments
256 if ( parameter_1
!== undefined ) {
257 parameters
= $.makeArray( arguments
);
262 return new Message( mw
.messages
, key
, parameters
);
266 * Gets a message string, similar to wfMsg()
268 * @param key string Key of message to get
269 * @param parameters mixed First argument in a list of variadic arguments,
270 * each a parameter for $N replacement in messages.
273 this.msg = function( key
, parameters
) {
274 return mw
.message
.apply( mw
.message
, arguments
).toString();
278 * Client-side module loader which integrates with the MediaWiki ResourceLoader
280 this.loader
= new ( function() {
282 /* Private Members */
285 * Mapping of registered modules
287 * The jquery module is pre-registered, because it must have already
288 * been provided for this object to have been built, and in debug mode
289 * jquery would have been provided through a unique loader request,
290 * making it impossible to hold back registration of jquery until after
296 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
297 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
298 * 'script': function() {},
299 * 'style': 'css code string',
300 * 'messages': { 'key': 'value' },
301 * 'version': ############## (unix timestamp)
306 // List of modules which will be loaded as when ready
308 // List of modules to be loaded
310 // List of callback functions waiting for modules to be ready to be called
312 // Flag inidicating that document ready has occured
314 // Selector cache for the marker element. Use getMarker() to get/use the marker!
317 /* Private Methods */
319 function getMarker(){
324 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
325 if ( $marker
.length
) {
328 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
329 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
334 function compare( a
, b
) {
335 if ( a
.length
!= b
.length
) {
338 for ( var i
= 0; i
< b
.length
; i
++ ) {
339 if ( $.isArray( a
[i
] ) ) {
340 if ( !compare( a
[i
], b
[i
] ) ) {
344 if ( a
[i
] !== b
[i
] ) {
352 * Generates an ISO8601 "basic" string from a UNIX timestamp
354 function formatVersionNumber( timestamp
) {
355 function pad( a
, b
, c
) {
356 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
359 d
.setTime( timestamp
* 1000 );
361 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
362 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
367 * Recursively resolves dependencies and detects circular references
369 function recurse( module
, resolved
, unresolved
) {
370 if ( registry
[module
] === undefined ) {
371 throw new Error( 'Unknown dependency: ' + module
);
373 // Resolves dynamic loader function and replaces it with its own results
374 if ( $.isFunction( registry
[module
].dependencies
) ) {
375 registry
[module
].dependencies
= registry
[module
].dependencies();
376 // Ensures the module's dependencies are always in an array
377 if ( typeof registry
[module
].dependencies
!== 'object' ) {
378 registry
[module
].dependencies
= [registry
[module
].dependencies
];
381 // Tracks down dependencies
382 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
383 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
384 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
386 'Circular reference detected: ' + module
+
387 ' -> ' + registry
[module
].dependencies
[n
]
390 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
393 resolved
[resolved
.length
] = module
;
394 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
398 * Gets a list of module names that a module depends on in their proper dependency order
400 * @param module string module name or array of string module names
401 * @return list of dependencies
402 * @throws Error if circular reference is detected
404 function resolve( module
) {
405 // Allow calling with an array of module names
406 if ( typeof module
=== 'object' ) {
408 for ( var m
= 0; m
< module
.length
; m
++ ) {
409 var dependencies
= resolve( module
[m
] );
410 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
411 modules
[modules
.length
] = dependencies
[n
];
415 } else if ( typeof module
=== 'string' ) {
416 // Undefined modules have no dependencies
417 if ( !( module
in registry
) ) {
421 recurse( module
, resolved
, [] );
424 throw new Error( 'Invalid module argument: ' + module
);
428 * Narrows a list of module names down to those matching a specific
429 * state. Possible states are 'undefined', 'registered', 'loading',
430 * 'loaded', or 'ready'
432 * @param states string or array of strings of module states to filter by
433 * @param modules array list of module names to filter (optional, all modules
434 * will be used by default)
435 * @return array list of filtered module names
437 function filter( states
, modules
) {
438 // Allow states to be given as a string
439 if ( typeof states
=== 'string' ) {
442 // If called without a list of modules, build and use a list of all modules
443 var list
= [], module
;
444 if ( modules
=== undefined ) {
446 for ( module
in registry
) {
447 modules
[modules
.length
] = module
;
450 // Build a list of modules which are in one of the specified states
451 for ( var s
= 0; s
< states
.length
; s
++ ) {
452 for ( var m
= 0; m
< modules
.length
; m
++ ) {
453 if ( registry
[modules
[m
]] === undefined ) {
454 // Module does not exist
455 if ( states
[s
] == 'undefined' ) {
457 list
[list
.length
] = modules
[m
];
460 // Module exists, check state
461 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
463 list
[list
.length
] = modules
[m
];
472 * Executes a loaded module, making it ready to use
474 * @param module string module name to execute
476 function execute( module
, callback
) {
477 var _fn
= 'mw.loader::execute> ';
478 if ( registry
[module
] === undefined ) {
479 throw new Error( 'Module has not been registered yet: ' + module
);
480 } else if ( registry
[module
].state
=== 'registered' ) {
481 throw new Error( 'Module has not been requested from the server yet: ' + module
);
482 } else if ( registry
[module
].state
=== 'loading' ) {
483 throw new Error( 'Module has not completed loading yet: ' + module
);
484 } else if ( registry
[module
].state
=== 'ready' ) {
485 throw new Error( 'Module has already been loaded: ' + module
);
488 if ( $.isPlainObject( registry
[module
].style
) ) {
489 for ( var media
in registry
[module
].style
) {
490 var style
= registry
[module
].style
[media
];
491 if ( $.isArray( style
) ) {
492 for ( var i
= 0; i
< style
.length
; i
++ ) {
493 getMarker().before( mw
.html
.element( 'link', {
499 } else if ( typeof style
=== 'string' ) {
500 getMarker().before( mw
.html
.element(
502 { 'type': 'text/css', 'media': media
},
503 new mw
.html
.Cdata( style
)
508 // Add localizations to message system
509 if ( $.isPlainObject( registry
[module
].messages
) ) {
510 mw
.messages
.set( registry
[module
].messages
);
514 var script
= registry
[module
].script
;
515 var markModuleReady = function() {
516 registry
[module
].state
= 'ready';
517 handlePending( module
);
518 if ( $.isFunction( callback
) ) {
522 if ( $.isArray( script
) ) {
524 if ( script
.length
=== 0 ) {
525 // No scripts in this module? Let's dive out early.
528 for ( var i
= 0; i
< script
.length
; i
++ ) {
529 registry
[module
].state
= 'loading';
530 addScript( script
[i
], function() {
531 if ( ++done
== script
.length
) {
536 } else if ( $.isFunction( script
) ) {
541 // This needs to NOT use mw.log because these errors are common in production mode
542 // and not in debug mode, such as when a symbol that should be global isn't exported
543 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
544 console
.log( _fn
+ 'Exception thrown by ' + module
+ ': ' + e
.message
);
546 registry
[module
].state
= 'error';
552 * Automatically executes jobs and modules which are pending with satistifed dependencies.
554 * This is used when dependencies are satisfied, such as when a module is executed.
556 function handlePending( module
) {
558 // Run jobs who's dependencies have just been met
559 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
561 filter( 'ready', jobs
[j
].dependencies
),
562 jobs
[j
].dependencies
) )
564 if ( $.isFunction( jobs
[j
].ready
) ) {
571 // Execute modules who's dependencies have just been met
572 for ( var r
in registry
) {
573 if ( registry
[r
].state
== 'loaded' ) {
575 filter( ['ready'], registry
[r
].dependencies
),
576 registry
[r
].dependencies
) )
583 // Run error callbacks of jobs affected by this condition
584 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
585 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
586 if ( $.isFunction( jobs
[j
].error
) ) {
597 * Adds a dependencies to the queue with optional callbacks to be run
598 * when the dependencies are ready or fail
600 * @param dependencies string module name or array of string module names
601 * @param ready function callback to execute when all dependencies are ready
602 * @param error function callback to execute when any dependency fails
604 function request( dependencies
, ready
, error
) {
605 // Allow calling by single module name
606 if ( typeof dependencies
=== 'string' ) {
607 dependencies
= [dependencies
];
608 if ( dependencies
[0] in registry
) {
609 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
610 dependencies
[dependencies
.length
] =
611 registry
[dependencies
[0]].dependencies
[n
];
615 // Add ready and error callbacks if they were given
616 if ( arguments
.length
> 1 ) {
617 jobs
[jobs
.length
] = {
618 'dependencies': filter(
619 ['undefined', 'registered', 'loading', 'loaded'],
625 // Queue up any dependencies that are undefined or registered
626 dependencies
= filter( ['undefined', 'registered'], dependencies
);
627 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
628 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
629 queue
[queue
.length
] = dependencies
[n
];
636 function sortQuery(o
) {
637 var sorted
= {}, key
, a
= [];
639 if ( o
.hasOwnProperty( key
) ) {
644 for ( key
= 0; key
< a
.length
; key
++ ) {
645 sorted
[a
[key
]] = o
[a
[key
]];
651 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
652 * to a query string of the form foo.bar,baz|bar.baz,quux
654 function buildModulesString( moduleMap
) {
656 for ( var prefix
in moduleMap
) {
657 var p
= prefix
=== '' ? '' : prefix
+ '.';
658 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
660 return arr
.join( '|' );
664 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
665 * depending on whether document-ready has occured yet.
667 * @param src String: URL to script, will be used as the src attribute in the script tag
668 * @param callback Function: Optional callback which will be run when the script is done
670 function addScript( src
, callback
) {
672 // jQuery's getScript method is NOT better than doing this the old-fassioned way
673 // because jQuery will eval the script's code, and errors will not have sane
675 var script
= document
.createElement( 'script' );
676 script
.setAttribute( 'src', src
);
677 script
.setAttribute( 'type', 'text/javascript' );
678 if ( $.isFunction( callback
) ) {
680 // Attach handlers for all browsers -- this is based on jQuery.getScript
681 script
.onload
= script
.onreadystatechange = function() {
686 || this.readyState
=== 'loaded'
687 || this.readyState
=== 'complete'
692 // Handle memory leak in IE
693 script
.onload
= script
.onreadystatechange
= null;
694 if ( script
.parentNode
) {
695 script
.parentNode
.removeChild( script
);
700 document
.body
.appendChild( script
);
702 document
.write( mw
.html
.element(
703 'script', { 'type': 'text/javascript', 'src': src
}, ''
705 if ( $.isFunction( callback
) ) {
706 // Document.write is synchronous, so this is called when it's done
715 * Requests dependencies from server, loading and executing when things when ready.
717 this.work = function() {
718 // Appends a list of modules to the batch
719 for ( var q
= 0; q
< queue
.length
; q
++ ) {
720 // Only request modules which are undefined or registered
721 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
722 // Prevent duplicate entries
723 if ( $.inArray( queue
[q
], batch
) === -1 ) {
724 batch
[batch
.length
] = queue
[q
];
725 // Mark registered modules as loading
726 if ( queue
[q
] in registry
) {
727 registry
[queue
[q
]].state
= 'loading';
732 // Early exit if there's nothing to load
733 if ( !batch
.length
) {
736 // Clean up the queue
738 // Always order modules alphabetically to help reduce cache
739 // misses for otherwise identical content
741 // Build a list of request parameters
743 'skin': mw
.config
.get( 'skin' ),
744 'lang': mw
.config
.get( 'wgUserLanguage' ),
745 'debug': mw
.config
.get( 'debug' )
747 // Extend request parameters with a list of modules in the batch
751 for ( var b
= 0; b
< batch
.length
; b
++ ) {
752 var group
= registry
[batch
[b
]].group
;
753 if ( !( group
in groups
) ) {
756 groups
[group
][groups
[group
].length
] = batch
[b
];
758 for ( var group
in groups
) {
759 // Calculate the highest timestamp
761 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
762 if ( registry
[groups
[group
][g
]].version
> version
) {
763 version
= registry
[groups
[group
][g
]].version
;
766 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
);
767 var reqBaseLength
= $.param( reqBase
).length
;
769 var limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
770 // We may need to split up the request to honor the query string length limit
771 // So build it piece by piece
772 var l
= reqBaseLength
+ 9; // '&modules='.length == 9
774 reqs
[0] = {}; // { prefix: [ suffixes ] }
775 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
776 // Determine how many bytes this module would add to the query string
777 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' );
778 // Note that these substr() calls work even if lastDotIndex == -1
779 var prefix
= groups
[group
][i
].substr( 0, lastDotIndex
);
780 var suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 );
781 var bytesAdded
= prefix
in reqs
[r
] ?
782 suffix
.length
+ 3 : // '%2C'.length == 3
783 groups
[group
][i
].length
+ 3; // '%7C'.length == 3
785 // If the request would become too long, create a new one,
786 // but don't create empty requests
787 if ( limit
> 0 && reqs
[r
] != {} && l
+ bytesAdded
> limit
) {
788 // This request would become too long, create a new one
791 l
= reqBaseLength
+ 9;
793 if ( !( prefix
in reqs
[r
] ) ) {
794 reqs
[r
][prefix
] = [];
796 reqs
[r
][prefix
].push( suffix
);
799 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
800 requests
[requests
.length
] = $.extend(
801 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
805 // Clear the batch - this MUST happen before we append the
806 // script element to the body or it's possible that the script
807 // will be locally cached, instantly load, and work the batch
808 // again, all before we've cleared it causing each request to
809 // include modules which are already loaded
811 // Asynchronously append a script tag to the end of the body
812 for ( var r
= 0; r
< requests
.length
; r
++ ) {
813 requests
[r
] = sortQuery( requests
[r
] );
814 // Append &* to avoid triggering the IE6 extension check
815 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] ) + '&*';
821 * Registers a module, letting the system know about it and its
822 * dependencies. loader.js files contain calls to this function.
824 this.register = function( module
, version
, dependencies
, group
) {
825 // Allow multiple registration
826 if ( typeof module
=== 'object' ) {
827 for ( var m
= 0; m
< module
.length
; m
++ ) {
828 if ( typeof module
[m
] === 'string' ) {
829 mw
.loader
.register( module
[m
] );
830 } else if ( typeof module
[m
] === 'object' ) {
831 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
837 if ( typeof module
!== 'string' ) {
838 throw new Error( 'module must be a string, not a ' + typeof module
);
840 if ( registry
[module
] !== undefined ) {
841 throw new Error( 'module already implemented: ' + module
);
843 // List the module as registered
845 'state': 'registered',
846 'group': typeof group
=== 'string' ? group
: null,
848 'version': version
!== undefined ? parseInt( version
, 10 ) : 0
850 if ( typeof dependencies
=== 'string' ) {
851 // Allow dependencies to be given as a single module name
852 registry
[module
].dependencies
= [dependencies
];
853 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
854 // Allow dependencies to be given as an array of module names
855 // or a function which returns an array
856 registry
[module
].dependencies
= dependencies
;
861 * Implements a module, giving the system a course of action to take
862 * upon loading. Results of a request for one or more modules contain
863 * calls to this function.
865 * All arguments are required.
867 * @param module String: Name of module
868 * @param script Mixed: Function of module code or String of URL to be used as the src
869 * attribute when adding a script element to the body
870 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
871 * keyed by media-type
872 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
874 this.implement = function( module
, script
, style
, msgs
) {
876 if ( typeof module
!== 'string' ) {
877 throw new Error( 'module must be a string, not a ' + typeof module
);
879 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
880 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
882 if ( !$.isPlainObject( style
) ) {
883 throw new Error( 'style must be an object, not a ' + typeof style
);
885 if ( !$.isPlainObject( msgs
) ) {
886 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
888 // Automatically register module
889 if ( registry
[module
] === undefined ) {
890 mw
.loader
.register( module
);
892 // Check for duplicate implementation
893 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
894 throw new Error( 'module already implemeneted: ' + module
);
896 // Mark module as loaded
897 registry
[module
].state
= 'loaded';
899 registry
[module
].script
= script
;
900 registry
[module
].style
= style
;
901 registry
[module
].messages
= msgs
;
902 // Execute or queue callback
904 filter( ['ready'], registry
[module
].dependencies
),
905 registry
[module
].dependencies
) )
914 * Executes a function as soon as one or more required modules are ready
916 * @param dependencies string or array of strings of modules names the callback
917 * dependencies to be ready before
919 * @param ready function callback to execute when all dependencies are ready (optional)
920 * @param error function callback to execute when if dependencies have a errors (optional)
922 this.using = function( dependencies
, ready
, error
) {
924 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
925 throw new Error( 'dependencies must be a string or an array, not a ' +
926 typeof dependencies
);
928 // Allow calling with a single dependency as a string
929 if ( typeof dependencies
=== 'string' ) {
930 dependencies
= [dependencies
];
932 // Resolve entire dependency map
933 dependencies
= resolve( dependencies
);
934 // If all dependencies are met, execute ready immediately
935 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
936 if ( $.isFunction( ready
) ) {
940 // If any dependencies have errors execute error immediately
941 else if ( filter( ['error'], dependencies
).length
) {
942 if ( $.isFunction( error
) ) {
946 // Since some dependencies are not yet ready, queue up a request
948 request( dependencies
, ready
, error
);
953 * Loads an external script or one or more modules for future use
955 * @param modules mixed either the name of a module, array of modules,
956 * or a URL of an external script or style
957 * @param type string mime-type to use if calling with a URL of an
958 * external script or style; acceptable values are "text/css" and
959 * "text/javascript"; if no type is provided, text/javascript is
962 this.load = function( modules
, type
) {
964 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
965 throw new Error( 'modules must be a string or an array, not a ' +
968 // Allow calling with an external script or single dependency as a string
969 if ( typeof modules
=== 'string' ) {
970 // Support adding arbitrary external scripts
971 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
972 if ( type
=== 'text/css' ) {
973 $( 'head' ).append( $( '<link />', {
979 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
980 addScript( modules
);
986 // Called with single module
989 // Resolve entire dependency map
990 modules
= resolve( modules
);
991 // If all modules are ready, nothing dependency be done
992 if ( compare( filter( ['ready'], modules
), modules
) ) {
995 // If any modules have errors return false
996 else if ( filter( ['error'], modules
).length
) {
999 // Since some modules are not yet ready, queue up a request
1007 * Changes the state of a module
1009 * @param module string module name or object of module name/state pairs
1010 * @param state string state name
1012 this.state = function( module
, state
) {
1013 if ( typeof module
=== 'object' ) {
1014 for ( var m
in module
) {
1015 mw
.loader
.state( m
, module
[m
] );
1019 if ( !( module
in registry
) ) {
1020 mw
.loader
.register( module
);
1022 registry
[module
].state
= state
;
1026 * Gets the version of a module
1028 * @param module string name of module to get version for
1030 this.getVersion = function( module
) {
1031 if ( module
in registry
&& 'version' in registry
[module
] ) {
1032 return formatVersionNumber( registry
[module
].version
);
1037 * @deprecated use mw.loader.getVersion() instead
1039 this.version = function() {
1040 return mediaWiki
.loader
.getVersion
.apply( mediaWiki
.loader
, arguments
);
1044 * Gets the state of a module
1046 * @param module string name of module to get state for
1048 this.getState = function( module
) {
1049 if ( module
in registry
&& 'state' in registry
[module
] ) {
1050 return registry
[module
].state
;
1055 /* Cache document ready status */
1057 $(document
).ready( function() { ready
= true; } );
1060 /** HTML construction helper functions */
1061 this.html
= new ( function () {
1062 var escapeCallback = function( s
) {
1078 * Escape a string for HTML. Converts special characters to HTML entities.
1079 * @param s The string to escape
1081 this.escape = function( s
) {
1082 return s
.replace( /['"<>&]/g, escapeCallback
);
1086 * Wrapper object for raw HTML passed to mw.html.element().
1088 this.Raw = function( value
) {
1093 * Wrapper object for CDATA element contents passed to mw.html.element()
1095 this.Cdata = function( value
) {
1100 * Create an HTML element string, with safe escaping.
1102 * @param name The tag name.
1103 * @param attrs An object with members mapping element names to values
1104 * @param contents The contents of the element. May be either:
1105 * - string: The string is escaped.
1106 * - null or undefined: The short closing form is used, e.g. <br/>.
1107 * - this.Raw: The value attribute is included without escaping.
1108 * - this.Cdata: The value attribute is included, and an exception is
1109 * thrown if it contains an illegal ETAGO delimiter.
1110 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1114 * return h.element( 'div', {},
1115 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1116 * Returns <div><img src="<"/></div>
1118 this.element = function( name
, attrs
, contents
) {
1120 for ( var attrName
in attrs
) {
1121 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1123 if ( contents
=== undefined || contents
=== null ) {
1130 if ( typeof contents
=== 'string' ) {
1132 s
+= this.escape( contents
);
1133 } else if ( contents
instanceof this.Raw
) {
1134 // Raw HTML inclusion
1135 s
+= contents
.value
;
1136 } else if ( contents
instanceof this.Cdata
) {
1138 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1139 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1141 s
+= contents
.value
;
1143 throw new Error( 'mw.html.element: Invalid type of contents' );
1145 s
+= '</' + name
+ '>';
1150 /* Extension points */
1156 // Alias $j to jQuery for backwards compatibility
1160 window
.mw
= mediaWiki
;
1162 /* Auto-register from pre-loaded startup scripts */
1164 if ( jQuery
.isFunction( startUp
) ) {