b78fdd882dac713168a0fa7301623b1ae34d3bb1
2 * Core MediaWiki JavaScript Library
5 // Attach to window and globally alias
6 window
.mw
= window
.mediaWiki
= new ( function( $ ) {
11 * @var object List of messages that have been requested to be loaded.
13 var messageQueue
= {};
15 /* Object constructors */
20 * Creates an object that can be read from or written to from prototype functions
21 * that allow both single and multiple variables at once.
23 * @param global boolean Whether to store the values in the global window
24 * object or a exclusively in the object property 'values'.
27 function Map( global
) {
28 this.values
= ( global
=== true ) ? window
: {};
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!).
43 * @return Values as a string or object, null if invalid/inexistant.
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
];
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 bool This returns true on success, false on failure.
76 Map
.prototype.set = function( selection
, value
) {
77 if ( $.isPlainObject( selection
) ) {
78 for ( var s
in selection
) {
79 this.values
[s
] = selection
[s
];
82 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
83 this.values
[selection
] = value
;
90 * Checks if one or multiple keys exist.
92 * @param selection mixed String key or array of keys to check
93 * @return boolean Existence of key(s)
95 Map
.prototype.exists = function( selection
) {
96 if ( typeof selection
=== 'object' ) {
97 for ( var s
= 0; s
< selection
.length
; s
++ ) {
98 if ( !( selection
[s
] in this.values
) ) {
104 return selection
in this.values
;
111 * Object constructor for messages,
112 * similar to the Message class in MediaWiki PHP.
114 * @param map Map Instance of mw.Map
116 * @param parameters Array
119 function Message( map
, key
, parameters
) {
120 this.format
= 'parse';
123 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
128 * Appends (does not replace) parameters for replacement to the .parameters property.
130 * @param parameters Array
133 Message
.prototype.params = function( parameters
) {
134 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
135 this.parameters
.push( parameters
[i
] );
141 * Converts message object to it's string form based on the state of format.
143 * @return string Message as a string in the current form or <key> if key does not exist.
145 Message
.prototype.toString = function() {
146 if ( !this.map
.exists( this.key
) ) {
147 // Return <key> if key does not exist
148 return '<' + this.key
+ '>';
150 var text
= this.map
.get( this.key
);
151 parameters
= this.parameters
;
153 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
154 var index
= parseInt( match
, 10 ) - 1;
155 return index
in parameters
? parameters
[index
] : '$' + match
;
158 if ( this.format
=== 'plain' ) {
161 if ( this.format
=== 'escaped' ) {
162 // According to Message.php this needs {{-transformation, which is
164 return mw
.html
.escape( text
);
167 /* This should be fixed up when we have a parser
168 if ( this.format === 'parse' && 'language' in mw ) {
169 text = mw.language.parse( text );
176 * Changes format to parse and converts message to string
178 * @return {string} String form of parsed message
180 Message
.prototype.parse = function() {
181 this.format
= 'parse';
182 return this.toString();
186 * Changes format to plain and converts message to string
188 * @return {string} String form of plain message
190 Message
.prototype.plain = function() {
191 this.format
= 'plain';
192 return this.toString();
196 * Changes the format to html escaped and converts message to string
198 * @return {string} String form of html escaped message
200 Message
.prototype.escaped = function() {
201 this.format
= 'escaped';
202 return this.toString();
206 * Checks if message exists
208 * @return {string} String form of parsed message
210 Message
.prototype.exists = function() {
211 return this.map
.exists( this.key
);
217 * Dummy function which in debug mode can be replaced with a function that
218 * emulates console.log in console-less environments.
220 this.log = function() { };
223 * @var constructor Make the Map constructor publicly available.
228 * List of configuration values
230 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
231 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
232 * in the global window object.
239 * Empty object that plugins can be installed in.
244 * Localization system
246 this.messages
= new this.Map();
251 * Gets a message object, similar to wfMessage()
253 * @param key string Key of message to get
254 * @param parameter_1 mixed First argument in a list of variadic arguments,
255 * each a parameter for $N replacement in messages.
258 this.message = function( key
, parameter_1
/* [, parameter_2] */ ) {
260 // Support variadic arguments
261 if ( parameter_1
!== undefined ) {
262 parameters
= $.makeArray( arguments
);
267 return new Message( mw
.messages
, key
, parameters
);
271 * Gets a message string, similar to wfMsg()
273 * @param key string Key of message to get
274 * @param parameters mixed First argument in a list of variadic arguments,
275 * each a parameter for $N replacement in messages.
278 this.msg = function( key
, parameters
) {
279 return mw
.message
.apply( mw
.message
, arguments
).toString();
283 * Client-side module loader which integrates with the MediaWiki ResourceLoader
285 this.loader
= new ( function() {
287 /* Private Members */
290 * Mapping of registered modules
292 * The jquery module is pre-registered, because it must have already
293 * been provided for this object to have been built, and in debug mode
294 * jquery would have been provided through a unique loader request,
295 * making it impossible to hold back registration of jquery until after
301 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
302 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
303 * 'script': function() {},
304 * 'style': 'css code string',
305 * 'messages': { 'key': 'value' },
306 * 'version': ############## (unix timestamp)
310 // List of modules which will be loaded as when ready
312 // List of modules to be loaded
314 // List of callback functions waiting for modules to be ready to be called
316 // Flag inidicating that document ready has occured
318 // Selector cache for the marker element. Use getMarker() to get/use the marker!
321 /* Private Methods */
323 function getMarker(){
328 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
329 if ( $marker
.length
) {
332 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
333 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
338 function compare( a
, b
) {
339 if ( a
.length
!== b
.length
) {
342 for ( var i
= 0; i
< b
.length
; i
++ ) {
343 if ( $.isArray( a
[i
] ) ) {
344 if ( !compare( a
[i
], b
[i
] ) ) {
348 if ( a
[i
] !== b
[i
] ) {
356 * Generates an ISO8601 "basic" string from a UNIX timestamp
358 function formatVersionNumber( timestamp
) {
359 var pad = function( a
, b
, c
) {
360 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
362 d
= new Date().setTime( timestamp
* 1000 );
364 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
365 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
370 * Recursively resolves dependencies and detects circular references
372 function recurse( module
, resolved
, unresolved
) {
373 if ( registry
[module
] === undefined ) {
374 throw new Error( 'Unknown dependency: ' + module
);
376 // Resolves dynamic loader function and replaces it with its own results
377 if ( $.isFunction( registry
[module
].dependencies
) ) {
378 registry
[module
].dependencies
= registry
[module
].dependencies();
379 // Ensures the module's dependencies are always in an array
380 if ( typeof registry
[module
].dependencies
!== 'object' ) {
381 registry
[module
].dependencies
= [registry
[module
].dependencies
];
384 // Tracks down dependencies
385 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
386 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
387 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
389 'Circular reference detected: ' + module
+
390 ' -> ' + registry
[module
].dependencies
[n
]
393 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
396 resolved
[resolved
.length
] = module
;
397 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
401 * Gets a list of module names that a module depends on in their proper dependency order
403 * @param module string module name or array of string module names
404 * @return list of dependencies
405 * @throws Error if circular reference is detected
407 function resolve( module
) {
408 // Allow calling with an array of module names
409 if ( typeof module
=== 'object' ) {
411 for ( var m
= 0; m
< module
.length
; m
++ ) {
412 var dependencies
= resolve( module
[m
] );
413 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
414 modules
[modules
.length
] = dependencies
[n
];
418 } else if ( typeof module
=== 'string' ) {
419 // Undefined modules have no dependencies
420 if ( !( module
in registry
) ) {
424 recurse( module
, resolved
, [] );
427 throw new Error( 'Invalid module argument: ' + module
);
431 * Narrows a list of module names down to those matching a specific
432 * state. Possible states are 'undefined', 'registered', 'loading',
433 * 'loaded', or 'ready'
435 * @param states string or array of strings of module states to filter by
436 * @param modules array list of module names to filter (optional, all modules
437 * will be used by default)
438 * @return array list of filtered module names
440 function filter( states
, modules
) {
441 // Allow states to be given as a string
442 if ( typeof states
=== 'string' ) {
445 // If called without a list of modules, build and use a list of all modules
446 var list
= [], module
;
447 if ( modules
=== undefined ) {
449 for ( module
in registry
) {
450 modules
[modules
.length
] = module
;
453 // Build a list of modules which are in one of the specified states
454 for ( var s
= 0; s
< states
.length
; s
++ ) {
455 for ( var m
= 0; m
< modules
.length
; m
++ ) {
456 if ( registry
[modules
[m
]] === undefined ) {
457 // Module does not exist
458 if ( states
[s
] === 'undefined' ) {
460 list
[list
.length
] = modules
[m
];
463 // Module exists, check state
464 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
466 list
[list
.length
] = modules
[m
];
475 * Executes a loaded module, making it ready to use
477 * @param module string module name to execute
479 function execute( module
, callback
) {
480 if ( registry
[module
] === undefined ) {
481 throw new Error( 'Module has not been registered yet: ' + module
);
482 } else if ( registry
[module
].state
=== 'registered' ) {
483 throw new Error( 'Module has not been requested from the server yet: ' + module
);
484 } else if ( registry
[module
].state
=== 'loading' ) {
485 throw new Error( 'Module has not completed loading yet: ' + module
);
486 } else if ( registry
[module
].state
=== 'ready' ) {
487 throw new Error( 'Module has already been loaded: ' + module
);
491 if ( $.isPlainObject( registry
[module
].style
) ) {
492 for ( var media
in registry
[module
].style
) {
493 style
= registry
[module
].style
[media
];
494 if ( $.isArray( style
) ) {
495 for ( var i
= 0; i
< style
.length
; i
++ ) {
496 getMarker().before( mw
.html
.element( 'link', {
502 } else if ( typeof style
=== 'string' ) {
503 getMarker().before( mw
.html
.element(
505 { 'type': 'text/css', 'media': media
},
506 new mw
.html
.Cdata( style
)
511 // Add localizations to message system
512 if ( $.isPlainObject( registry
[module
].messages
) ) {
513 mw
.messages
.set( registry
[module
].messages
);
517 var script
= registry
[module
].script
,
518 markModuleReady = function() {
519 registry
[module
].state
= 'ready';
520 handlePending( module
);
521 if ( $.isFunction( callback
) ) {
526 if ( $.isArray( script
) ) {
528 if ( script
.length
=== 0 ) {
529 // No scripts in this module? Let's dive out early.
532 for ( var i
= 0; i
< script
.length
; i
++ ) {
533 registry
[module
].state
= 'loading';
534 addScript( script
[i
], function() {
535 if ( ++done
=== script
.length
) {
540 } else if ( $.isFunction( script
) ) {
545 // This needs to NOT use mw.log because these errors are common in production mode
546 // and not in debug mode, such as when a symbol that should be global isn't exported
547 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
548 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
550 registry
[module
].state
= 'error';
556 * Automatically executes jobs and modules which are pending with satistifed dependencies.
558 * This is used when dependencies are satisfied, such as when a module is executed.
560 function handlePending( module
) {
562 // Run jobs who's dependencies have just been met
563 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
565 filter( 'ready', jobs
[j
].dependencies
),
566 jobs
[j
].dependencies
) )
568 if ( $.isFunction( jobs
[j
].ready
) ) {
575 // Execute modules who's dependencies have just been met
576 for ( var r
in registry
) {
577 if ( registry
[r
].state
=== 'loaded' ) {
579 filter( ['ready'], registry
[r
].dependencies
),
580 registry
[r
].dependencies
) )
587 // Run error callbacks of jobs affected by this condition
588 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
589 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
590 if ( $.isFunction( jobs
[j
].error
) ) {
601 * Adds a dependencies to the queue with optional callbacks to be run
602 * when the dependencies are ready or fail
604 * @param dependencies string module name or array of string module names
605 * @param ready function callback to execute when all dependencies are ready
606 * @param error function callback to execute when any dependency fails
608 function request( dependencies
, ready
, error
) {
609 // Allow calling by single module name
610 if ( typeof dependencies
=== 'string' ) {
611 dependencies
= [dependencies
];
612 if ( dependencies
[0] in registry
) {
613 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
614 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
618 // Add ready and error callbacks if they were given
619 if ( arguments
.length
> 1 ) {
620 jobs
[jobs
.length
] = {
621 'dependencies': filter(
622 ['undefined', 'registered', 'loading', 'loaded'],
629 // Queue up any dependencies that are undefined or registered
630 dependencies
= filter( ['undefined', 'registered'], dependencies
);
631 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
632 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
633 queue
[queue
.length
] = dependencies
[n
];
640 function sortQuery(o
) {
641 var sorted
= {}, key
, a
= [];
643 if ( o
.hasOwnProperty( key
) ) {
648 for ( key
= 0; key
< a
.length
; key
++ ) {
649 sorted
[a
[key
]] = o
[a
[key
]];
655 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
656 * to a query string of the form foo.bar,baz|bar.baz,quux
658 function buildModulesString( moduleMap
) {
660 for ( var prefix
in moduleMap
) {
661 p
= prefix
=== '' ? '' : prefix
+ '.';
662 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
664 return arr
.join( '|' );
668 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
669 * depending on whether document-ready has occured yet.
671 * @param src String: URL to script, will be used as the src attribute in the script tag
672 * @param callback Function: Optional callback which will be run when the script is done
674 function addScript( src
, callback
) {
676 // jQuery's getScript method is NOT better than doing this the old-fassioned way
677 // because jQuery will eval the script's code, and errors will not have sane
680 script
= document
.createElement( 'script' );
681 script
.setAttribute( 'src', src
);
682 script
.setAttribute( 'type', 'text/javascript' );
683 if ( $.isFunction( callback
) ) {
684 // Attach handlers for all browsers -- this is based on jQuery.getScript
685 script
.onload
= script
.onreadystatechange = function() {
690 || this.readyState
=== 'loaded'
691 || this.readyState
=== 'complete'
696 // Handle memory leak in IE
697 script
.onload
= script
.onreadystatechange
= null;
698 if ( script
.parentNode
) {
699 script
.parentNode
.removeChild( script
);
704 document
.body
.appendChild( script
);
706 document
.write( mw
.html
.element(
707 'script', { 'type': 'text/javascript', 'src': src
}, ''
709 if ( $.isFunction( callback
) ) {
710 // Document.write is synchronous, so this is called when it's done
719 * Requests dependencies from server, loading and executing when things when ready.
721 this.work = function() {
722 // Build a list of request parameters
724 'skin': mw
.config
.get( 'skin' ),
725 'lang': mw
.config
.get( 'wgUserLanguage' ),
726 'debug': mw
.config
.get( 'debug' )
728 // Extend request parameters with a list of modules in the batch
733 // Appends a list of modules to the batch
734 for ( var q
= 0; q
< queue
.length
; q
++ ) {
735 // Only request modules which are undefined or registered
736 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
=== 'registered' ) {
737 // Prevent duplicate entries
738 if ( $.inArray( queue
[q
], batch
) === -1 ) {
739 batch
[batch
.length
] = queue
[q
];
740 // Mark registered modules as loading
741 if ( queue
[q
] in registry
) {
742 registry
[queue
[q
]].state
= 'loading';
747 // Early exit if there's nothing to load
748 if ( !batch
.length
) {
751 // Clean up the queue
753 // Always order modules alphabetically to help reduce cache
754 // misses for otherwise identical content
756 for ( var b
= 0; b
< batch
.length
; b
++ ) {
757 var bGroup
= registry
[batch
[b
]].group
;
758 if ( !( bGroup
in groups
) ) {
761 groups
[bGroup
][groups
[bGroup
].length
] = batch
[b
];
763 for ( var group
in groups
) {
764 // Calculate the highest timestamp
766 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
767 if ( registry
[groups
[group
][g
]].version
> version
) {
768 version
= registry
[groups
[group
][g
]].version
;
772 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
),
773 reqBaseLength
= $.param( reqBase
).length
,
775 limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 ),
776 // We may need to split up the request to honor the query string length limit,
777 // so build it piece by piece.
778 l
= reqBaseLength
+ 9, // '&modules='.length == 9
781 reqs
[0] = {}; // { prefix: [ suffixes ] }
783 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
784 // Determine how many bytes this module would add to the query string
785 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' ),
786 // Note that these substr() calls work even if lastDotIndex == -1
787 prefix
= groups
[group
][i
].substr( 0, lastDotIndex
),
788 suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 ),
789 bytesAdded
= prefix
in reqs
[r
]
790 ? suffix
.length
+ 3 // '%2C'.length == 3
791 : groups
[group
][i
].length
+ 3; // '%7C'.length == 3
793 // If the request would become too long, create a new one,
794 // but don't create empty requests
795 if ( limit
> 0 && !$.isEmptyObject( reqs
[r
] ) && l
+ bytesAdded
> limit
) {
796 // This request would become too long, create a new one
799 l
= reqBaseLength
+ 9;
801 if ( !( prefix
in reqs
[r
] ) ) {
802 reqs
[r
][prefix
] = [];
804 reqs
[r
][prefix
].push( suffix
);
807 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
808 requests
[requests
.length
] = $.extend(
809 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
813 // Clear the batch - this MUST happen before we append the
814 // script element to the body or it's possible that the script
815 // will be locally cached, instantly load, and work the batch
816 // again, all before we've cleared it causing each request to
817 // include modules which are already loaded
819 // Asynchronously append a script tag to the end of the body
820 for ( var r
= 0; r
< requests
.length
; r
++ ) {
821 requests
[r
] = sortQuery( requests
[r
] );
822 // Append &* to avoid triggering the IE6 extension check
823 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] ) + '&*';
829 * Registers a module, letting the system know about it and its
830 * dependencies. loader.js files contain calls to this function.
832 this.register = function( module
, version
, dependencies
, group
) {
833 // Allow multiple registration
834 if ( typeof module
=== 'object' ) {
835 for ( var m
= 0; m
< module
.length
; m
++ ) {
836 if ( typeof module
[m
] === 'string' ) {
837 mw
.loader
.register( module
[m
] );
838 } else if ( typeof module
[m
] === 'object' ) {
839 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
845 if ( typeof module
!== 'string' ) {
846 throw new Error( 'module must be a string, not a ' + typeof module
);
848 if ( registry
[module
] !== undefined ) {
849 throw new Error( 'module already implemented: ' + module
);
851 // List the module as registered
853 'state': 'registered',
854 'group': typeof group
=== 'string' ? group
: null,
856 'version': version
!== undefined ? parseInt( version
, 10 ) : 0
858 if ( typeof dependencies
=== 'string' ) {
859 // Allow dependencies to be given as a single module name
860 registry
[module
].dependencies
= [dependencies
];
861 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
862 // Allow dependencies to be given as an array of module names
863 // or a function which returns an array
864 registry
[module
].dependencies
= dependencies
;
869 * Implements a module, giving the system a course of action to take
870 * upon loading. Results of a request for one or more modules contain
871 * calls to this function.
873 * All arguments are required.
875 * @param module String: Name of module
876 * @param script Mixed: Function of module code or String of URL to be used as the src
877 * attribute when adding a script element to the body
878 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
879 * keyed by media-type
880 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
882 this.implement = function( module
, script
, style
, msgs
) {
884 if ( typeof module
!== 'string' ) {
885 throw new Error( 'module must be a string, not a ' + typeof module
);
887 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
888 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
890 if ( !$.isPlainObject( style
) ) {
891 throw new Error( 'style must be an object, not a ' + typeof style
);
893 if ( !$.isPlainObject( msgs
) ) {
894 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
896 // Automatically register module
897 if ( registry
[module
] === undefined ) {
898 mw
.loader
.register( module
);
900 // Check for duplicate implementation
901 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
902 throw new Error( 'module already implemeneted: ' + module
);
904 // Mark module as loaded
905 registry
[module
].state
= 'loaded';
907 registry
[module
].script
= script
;
908 registry
[module
].style
= style
;
909 registry
[module
].messages
= msgs
;
910 // Execute or queue callback
912 filter( ['ready'], registry
[module
].dependencies
),
913 registry
[module
].dependencies
) )
922 * Executes a function as soon as one or more required modules are ready
924 * @param dependencies string or array of strings of modules names the callback
925 * dependencies to be ready before executing
926 * @param ready function callback to execute when all dependencies are ready (optional)
927 * @param error function callback to execute when if dependencies have a errors (optional)
929 this.using = function( dependencies
, ready
, error
) {
930 var tod
= typeof dependencies
;
932 if ( tod
!== 'object' && tod
!== 'string' ) {
933 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
935 // Allow calling with a single dependency as a string
936 if ( tod
=== 'string' ) {
937 dependencies
= [dependencies
];
939 // Resolve entire dependency map
940 dependencies
= resolve( dependencies
);
941 // If all dependencies are met, execute ready immediately
942 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
943 if ( $.isFunction( ready
) ) {
947 // If any dependencies have errors execute error immediately
948 else if ( filter( ['error'], dependencies
).length
) {
949 if ( $.isFunction( error
) ) {
953 // Since some dependencies are not yet ready, queue up a request
955 request( dependencies
, ready
, error
);
960 * Loads an external script or one or more modules for future use
962 * @param modules mixed either the name of a module, array of modules,
963 * or a URL of an external script or style
964 * @param type string mime-type to use if calling with a URL of an
965 * external script or style; acceptable values are "text/css" and
966 * "text/javascript"; if no type is provided, text/javascript is assumed.
968 this.load = function( modules
, type
) {
970 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
971 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
973 // Allow calling with an external script or single dependency as a string
974 if ( typeof modules
=== 'string' ) {
975 // Support adding arbitrary external scripts
976 if ( modules
.substr( 0, 7 ) === 'http://' || modules
.substr( 0, 8 ) === 'https://' ) {
977 if ( type
=== 'text/css' ) {
978 $( 'head' ).append( $( '<link/>', {
984 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
985 addScript( modules
);
991 // Called with single module
994 // Resolve entire dependency map
995 modules
= resolve( modules
);
996 // If all modules are ready, nothing dependency be done
997 if ( compare( filter( ['ready'], modules
), modules
) ) {
1000 // If any modules have errors return false
1001 else if ( filter( ['error'], modules
).length
) {
1004 // Since some modules are not yet ready, queue up a request
1012 * Changes the state of a module
1014 * @param module string module name or object of module name/state pairs
1015 * @param state string state name
1017 this.state = function( module
, state
) {
1018 if ( typeof module
=== 'object' ) {
1019 for ( var m
in module
) {
1020 mw
.loader
.state( m
, module
[m
] );
1024 if ( !( module
in registry
) ) {
1025 mw
.loader
.register( module
);
1027 registry
[module
].state
= state
;
1031 * Gets the version of a module
1033 * @param module string name of module to get version for
1035 this.getVersion = function( module
) {
1036 if ( module
in registry
&& 'version' in registry
[module
] ) {
1037 return formatVersionNumber( registry
[module
].version
);
1043 * @deprecated use mw.loader.getVersion() instead
1045 this.version = function() {
1046 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1050 * Gets the state of a module
1052 * @param module string name of module to get state for
1054 this.getState = function( module
) {
1055 if ( module
in registry
&& 'state' in registry
[module
] ) {
1056 return registry
[module
].state
;
1061 /* Cache document ready status */
1063 $(document
).ready( function() { ready
= true; } );
1066 /** HTML construction helper functions */
1067 this.html
= new ( function () {
1068 var escapeCallback = function( s
) {
1084 * Escape a string for HTML. Converts special characters to HTML entities.
1085 * @param s The string to escape
1087 this.escape = function( s
) {
1088 return s
.replace( /['"<>&]/g, escapeCallback
);
1092 * Wrapper object for raw HTML passed to mw.html.element().
1094 this.Raw = function( value
) {
1099 * Wrapper object for CDATA element contents passed to mw.html.element()
1101 this.Cdata = function( value
) {
1106 * Create an HTML element string, with safe escaping.
1108 * @param name The tag name.
1109 * @param attrs An object with members mapping element names to values
1110 * @param contents The contents of the element. May be either:
1111 * - string: The string is escaped.
1112 * - null or undefined: The short closing form is used, e.g. <br/>.
1113 * - this.Raw: The value attribute is included without escaping.
1114 * - this.Cdata: The value attribute is included, and an exception is
1115 * thrown if it contains an illegal ETAGO delimiter.
1116 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1120 * return h.element( 'div', {},
1121 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1122 * Returns <div><img src="<"/></div>
1124 this.element = function( name
, attrs
, contents
) {
1126 for ( var attrName
in attrs
) {
1127 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1129 if ( contents
=== undefined || contents
=== null ) {
1136 if ( typeof contents
=== 'string' ) {
1138 s
+= this.escape( contents
);
1139 } else if ( contents
instanceof this.Raw
) {
1140 // Raw HTML inclusion
1141 s
+= contents
.value
;
1142 } else if ( contents
instanceof this.Cdata
) {
1144 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1145 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1147 s
+= contents
.value
;
1149 throw new Error( 'mw.html.element: Invalid type of contents' );
1151 s
+= '</' + name
+ '>';
1156 /* Extension points */
1162 // Alias $j to jQuery for backwards compatibility
1165 /* Auto-register from pre-loaded startup scripts */
1167 if ( jQuery
.isFunction( startUp
) ) {