2 * JavaScript backwards-compatibility alternatives and other convenience functions
6 trimLeft : function( str
) {
7 return str
=== null ? '' : str
.toString().replace( /^\s+/, '' );
9 trimRight : function( str
) {
11 '' : str
.toString().replace( /\s+$/, '' );
13 ucFirst : function( str
) {
14 return str
.substr( 0, 1 ).toUpperCase() + str
.substr( 1 );
16 escapeRE : function( str
) {
17 return str
.replace ( /([\\{}()|.?*+\-^$\[\]])/g, "\\$1" );
19 isDomElement : function( el
) {
20 return !!el
&& !!el
.nodeType
;
22 isEmpty : function( v
) {
24 if ( v
=== "" || v
=== 0 || v
=== "0" || v
=== null
25 || v
=== false || typeof v
=== 'undefined' )
29 // the for-loop could potentially contain prototypes
30 // to avoid that we check it's length first
31 if ( v
.length
=== 0 ) {
34 if ( typeof v
=== 'object' ) {
42 compareArray : function( arrThis
, arrAgainst
) {
43 if ( arrThis
.length
!= arrAgainst
.length
) {
46 for ( var i
= 0; i
< arrThis
.length
; i
++ ) {
47 if ( arrThis
[i
] instanceof Array
) {
48 if ( !$.compareArray( arrThis
[i
], arrAgainst
[i
] ) ) {
51 } else if ( arrThis
[i
] !== arrAgainst
[i
] ) {
57 compareObject : function( objectA
, objectB
) {
59 // Do a simple check if the types match
60 if ( typeof objectA
== typeof objectB
) {
62 // Only loop over the contents if it really is an object
63 if ( typeof objectA
== 'object' ) {
64 // If they are aliases of the same object (ie. mw and mediaWiki) return now
65 if ( objectA
=== objectB
) {
69 // Iterate over each property
70 for ( prop
in objectA
) {
71 // Check if this property is also present in the other object
72 if ( prop
in objectB
) {
73 // Compare the types of the properties
74 var type
= typeof objectA
[prop
];
75 if ( type
== typeof objectB
[prop
] ) {
76 // Recursively check objects inside this one
79 if ( !$.compareObject( objectA
[prop
], objectB
[prop
] ) ) {
84 // Functions need to be strings to compare them properly
85 if ( objectA
[prop
].toString() !== objectB
[prop
].toString() ) {
91 if ( objectA
[prop
] !== objectB
[prop
] ) {
103 // Check for properties in B but not in A
104 // This is about 15% faster (tested in Safari 5 and Firefox 3.6)
105 // ...than incrementing a count variable in the above and below loops
106 // See also: http://www.mediawiki.org/wiki/ResourceLoader/Default_modules/compareObject_test#Results
107 for ( prop
in objectB
) {
108 if ( !( prop
in objectA
) ) {
122 * Core MediaWiki JavaScript Library
126 window
.mediaWiki
= new ( function( $ ) {
130 /* Private Members */
132 // List of messages that have been requested to be loaded
133 var messageQueue
= {};
138 * An object which allows single and multiple get/set/exists functionality
139 * on a list of key / value pairs.
141 * @param {boolean} global Whether to get/set/exists values on the window
142 * object or a private object
144 function Map( global
) {
145 this.values
= ( global
=== true ) ? window
: {};
149 * Gets the value of a key, or a list of key/value pairs for an array of keys.
151 * If called with no arguments, all values will be returned.
153 * @param selection mixed Key or array of keys to get values for
154 * @param fallback mixed Value to use in case key(s) do not exist (optional)
156 Map
.prototype.get = function( selection
, fallback
) {
157 if ( typeof selection
=== 'object' ) {
158 selection
= $.makeArray( selection
);
160 for ( var i
= 0; i
< selection
.length
; i
++ ) {
161 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
164 } else if ( typeof selection
=== 'string' ) {
165 if ( typeof this.values
[selection
] === 'undefined' ) {
166 if ( typeof fallback
!== 'undefined' ) {
171 return this.values
[selection
];
177 * Sets one or multiple key/value pairs.
179 * @param selection mixed Key or object of key/value pairs to set
180 * @param value mixed Value to set (optional, only in use when key is a string)
182 Map
.prototype.set = function( selection
, value
) {
183 if ( typeof selection
=== 'object' ) {
184 for ( var s
in selection
) {
185 this.values
[s
] = selection
[s
];
188 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
189 this.values
[selection
] = value
;
196 * Checks if one or multiple keys exist.
198 * @param selection mixed Key or array of keys to check
199 * @return boolean Existence of key(s)
201 Map
.prototype.exists = function( selection
) {
202 if ( typeof selection
=== 'object' ) {
203 for ( var s
= 0; s
< selection
.length
; s
++ ) {
204 if ( !( selection
[s
] in this.values
) ) {
210 return selection
in this.values
;
215 * Message object, similar to Message in PHP
217 function Message( map
, key
, parameters
) {
218 this.format
= 'parse';
221 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
225 * Appends parameters for replacement
227 * @param parameters mixed First in a list of variadic arguments to append as message parameters
229 Message
.prototype.params = function( parameters
) {
230 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
231 this.parameters
[this.parameters
.length
] = parameters
[i
];
237 * Converts message object to it's string form based on the state of format
239 * @return {string} String form of message
241 Message
.prototype.toString = function() {
242 if ( !this.map
.exists( this.key
) ) {
243 // Return <key> if key does not exist
244 return '<' + this.key
+ '>';
246 var text
= this.map
.get( this.key
);
247 var parameters
= this.parameters
;
248 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
249 var index
= parseInt( match
, 10 ) - 1;
250 return index
in parameters
? parameters
[index
] : '$' + match
;
253 if ( this.format
=== 'plain' ) {
256 if ( this.format
=== 'escaped' ) {
257 // According to Message.php this needs {{-transformation, which is
259 return mw
.html
.escape( text
);
262 /* This should be fixed up when we have a parser
263 if ( this.format === 'parse' && 'language' in mediaWiki ) {
264 text = mw.language.parse( text );
271 * Changes format to parse and converts message to string
273 * @return {string} String form of parsed message
275 Message
.prototype.parse = function() {
276 this.format
= 'parse';
277 return this.toString();
281 * Changes format to plain and converts message to string
283 * @return {string} String form of plain message
285 Message
.prototype.plain = function() {
286 this.format
= 'plain';
287 return this.toString();
291 * Changes the format to html escaped and converts message to string
293 * @return {string} String form of html escaped message
295 Message
.prototype.escaped = function() {
296 this.format
= 'escaped';
297 return this.toString();
301 * Checks if message exists
303 * @return {string} String form of parsed message
305 Message
.prototype.exists = function() {
306 return this.map
.exists( this.key
);
312 * Dummy function which in debug mode can be replaced with a function that
313 * does something clever
315 this.log = function() { };
318 * Make the Map-class publicly available
323 * List of configuration values
325 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
326 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
327 * in the global window object.
332 * Localization system
334 this.messages
= new this.Map();
339 * Gets a message object, similar to wfMessage()
341 * @param key string Key of message to get
342 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
345 this.message = function( key
, parameters
) {
346 // Support variadic arguments
347 if ( typeof parameters
!== 'undefined' ) {
348 parameters
= $.makeArray( arguments
);
353 return new Message( mw
.messages
, key
, parameters
);
357 * Gets a message string, similar to wfMsg()
359 * @param key string Key of message to get
360 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
363 this.msg = function( key
, parameters
) {
364 return mw
.message
.apply( mw
.message
, arguments
).toString();
368 * Client-side module loader which integrates with the MediaWiki ResourceLoader
370 this.loader
= new ( function() {
372 /* Private Members */
375 * Mapping of registered modules
377 * The jquery module is pre-registered, because it must have already
378 * been provided for this object to have been built, and in debug mode
379 * jquery would have been provided through a unique loader request,
380 * making it impossible to hold back registration of jquery until after
386 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
387 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
388 * 'script': function() {},
389 * 'style': 'css code string',
390 * 'messages': { 'key': 'value' },
391 * 'version': ############## (unix timestamp)
396 // List of modules which will be loaded as when ready
398 // List of modules to be loaded
400 // List of callback functions waiting for modules to be ready to be called
402 // Flag inidicating that document ready has occured
404 // Selector cache for the marker element. Use getMarker() to get/use the marker!
407 /* Private Methods */
409 function getMarker(){
414 //mw.log( 'getMarker> Caching marker' );
415 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
416 if ( $marker
.length
) {
419 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
420 return $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
424 function compare( a
, b
) {
425 if ( a
.length
!= b
.length
) {
428 for ( var i
= 0; i
< b
.length
; i
++ ) {
429 if ( $.isArray( a
[i
] ) ) {
430 if ( !compare( a
[i
], b
[i
] ) ) {
434 if ( a
[i
] !== b
[i
] ) {
442 * Generates an ISO8601 "basic" string from a UNIX timestamp
444 function formatVersionNumber( timestamp
) {
445 function pad( a
, b
, c
) {
446 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
449 d
.setTime( timestamp
* 1000 );
451 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
452 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
457 * Recursively resolves dependencies and detects circular references
459 function recurse( module
, resolved
, unresolved
) {
460 if ( typeof registry
[module
] === 'undefined' ) {
461 throw new Error( 'Unknown dependency: ' + module
);
463 // Resolves dynamic loader function and replaces it with its own results
464 if ( $.isFunction( registry
[module
].dependencies
) ) {
465 registry
[module
].dependencies
= registry
[module
].dependencies();
466 // Ensures the module's dependencies are always in an array
467 if ( typeof registry
[module
].dependencies
!== 'object' ) {
468 registry
[module
].dependencies
= [registry
[module
].dependencies
];
471 // Tracks down dependencies
472 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
473 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
474 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
476 'Circular reference detected: ' + module
+
477 ' -> ' + registry
[module
].dependencies
[n
]
480 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
483 resolved
[resolved
.length
] = module
;
484 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
488 * Gets a list of module names that a module depends on in their proper dependency order
490 * @param module string module name or array of string module names
491 * @return list of dependencies
492 * @throws Error if circular reference is detected
494 function resolve( module
) {
495 // Allow calling with an array of module names
496 if ( typeof module
=== 'object' ) {
498 for ( var m
= 0; m
< module
.length
; m
++ ) {
499 var dependencies
= resolve( module
[m
] );
500 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
501 modules
[modules
.length
] = dependencies
[n
];
505 } else if ( typeof module
=== 'string' ) {
506 // Undefined modules have no dependencies
507 if ( !( module
in registry
) ) {
511 recurse( module
, resolved
, [] );
514 throw new Error( 'Invalid module argument: ' + module
);
518 * Narrows a list of module names down to those matching a specific
519 * state. Possible states are 'undefined', 'registered', 'loading',
520 * 'loaded', or 'ready'
522 * @param states string or array of strings of module states to filter by
523 * @param modules array list of module names to filter (optional, all modules
524 * will be used by default)
525 * @return array list of filtered module names
527 function filter( states
, modules
) {
528 // Allow states to be given as a string
529 if ( typeof states
=== 'string' ) {
532 // If called without a list of modules, build and use a list of all modules
533 var list
= [], module
;
534 if ( typeof modules
=== 'undefined' ) {
536 for ( module
in registry
) {
537 modules
[modules
.length
] = module
;
540 // Build a list of modules which are in one of the specified states
541 for ( var s
= 0; s
< states
.length
; s
++ ) {
542 for ( var m
= 0; m
< modules
.length
; m
++ ) {
543 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
544 // Module does not exist
545 if ( states
[s
] == 'undefined' ) {
547 list
[list
.length
] = modules
[m
];
550 // Module exists, check state
551 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
553 list
[list
.length
] = modules
[m
];
562 * Executes a loaded module, making it ready to use
564 * @param module string module name to execute
566 function execute( module
, callback
) {
567 var _fn
= 'mw.loader::execute> ';
568 if ( typeof registry
[module
] === 'undefined' ) {
569 throw new Error( 'Module has not been registered yet: ' + module
);
570 } else if ( registry
[module
].state
=== 'registered' ) {
571 throw new Error( 'Module has not been requested from the server yet: ' + module
);
572 } else if ( registry
[module
].state
=== 'loading' ) {
573 throw new Error( 'Module has not completed loading yet: ' + module
);
574 } else if ( registry
[module
].state
=== 'ready' ) {
575 throw new Error( 'Module has already been loaded: ' + module
);
578 if ( $.isPlainObject( registry
[module
].style
) ) {
579 for ( var media
in registry
[module
].style
) {
580 var style
= registry
[module
].style
[media
];
581 if ( $.isArray( style
) ) {
582 for ( var i
= 0; i
< style
.length
; i
++ ) {
583 getMarker().before( mw
.html
.element( 'link', {
589 } else if ( typeof style
=== 'string' ) {
590 getMarker().before( mw
.html
.element(
592 { 'type': 'text/css', 'media': media
},
593 new mw
.html
.Cdata( style
)
598 // Add localizations to message system
599 if ( $.isPlainObject( registry
[module
].messages
) ) {
600 mw
.messages
.set( registry
[module
].messages
);
604 var script
= registry
[module
].script
;
605 if ( $.isArray( script
) ) {
607 for ( var i
= 0; i
< script
.length
; i
++ ) {
608 registry
[module
].state
= 'loading';
609 addScript( script
[i
], function() {
610 if ( ++done
== script
.length
) {
611 registry
[module
].state
= 'ready';
613 if ( $.isFunction( callback
) ) {
619 } else if ( $.isFunction( script
) ) {
621 registry
[module
].state
= 'ready';
623 if ( $.isFunction( callback
) ) {
628 // This needs to NOT use mw.log because these errors are common in production mode
629 // and not in debug mode, such as when a symbol that should be global isn't exported
630 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
631 console
.log( _fn
+ 'Exception thrown by ' + module
+ ': ' + e
.message
);
634 registry
[module
].state
= 'error';
639 * Automatically executes jobs and modules which are pending with satistifed dependencies.
641 * This is used when dependencies are satisfied, such as when a module is executed.
643 function handlePending() {
645 // Run jobs who's dependencies have just been met
646 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
648 filter( 'ready', jobs
[j
].dependencies
),
649 jobs
[j
].dependencies
) )
651 if ( $.isFunction( jobs
[j
].ready
) ) {
658 // Execute modules who's dependencies have just been met
659 for ( var r
in registry
) {
660 if ( registry
[r
].state
== 'loaded' ) {
662 filter( ['ready'], registry
[r
].dependencies
),
663 registry
[r
].dependencies
) )
670 // Run error callbacks of jobs affected by this condition
671 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
672 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
673 if ( $.isFunction( jobs
[j
].error
) ) {
684 * Adds a dependencies to the queue with optional callbacks to be run
685 * when the dependencies are ready or fail
687 * @param dependencies string module name or array of string module names
688 * @param ready function callback to execute when all dependencies are ready
689 * @param error function callback to execute when any dependency fails
691 function request( dependencies
, ready
, error
) {
692 // Allow calling by single module name
693 if ( typeof dependencies
=== 'string' ) {
694 dependencies
= [dependencies
];
695 if ( dependencies
[0] in registry
) {
696 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
697 dependencies
[dependencies
.length
] =
698 registry
[dependencies
[0]].dependencies
[n
];
702 // Add ready and error callbacks if they were given
703 if ( arguments
.length
> 1 ) {
704 jobs
[jobs
.length
] = {
705 'dependencies': filter(
706 ['undefined', 'registered', 'loading', 'loaded'],
712 // Queue up any dependencies that are undefined or registered
713 dependencies
= filter( ['undefined', 'registered'], dependencies
);
714 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
715 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
716 queue
[queue
.length
] = dependencies
[n
];
723 function sortQuery(o
) {
724 var sorted
= {}, key
, a
= [];
726 if ( o
.hasOwnProperty( key
) ) {
731 for ( key
= 0; key
< a
.length
; key
++ ) {
732 sorted
[a
[key
]] = o
[a
[key
]];
738 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
739 * to a query string of the form foo.bar,baz|bar.baz,quux
741 function buildModulesString( moduleMap
) {
743 for ( var prefix
in moduleMap
) {
744 var p
= prefix
=== '' ? '' : prefix
+ '.';
745 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
747 return arr
.join( '|' ).replace( /\./g, '!' );
751 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
752 * depending on whether document-ready has occured yet.
754 * @param src String: URL to script, will be used as the src attribute in the script tag
755 * @param callback Function: Optional callback which will be run when the script is done
757 function addScript( src
, callback
) {
759 // jQuery's getScript method is NOT better than doing this the old-fassioned way
760 // because jQuery will eval the script's code, and errors will not have sane
762 var script
= document
.createElement( 'script' );
763 script
.setAttribute( 'src', src
);
764 script
.setAttribute( 'type', 'text/javascript' );
765 if ( $.isFunction( callback
) ) {
767 // Attach handlers for all browsers -- this is based on jQuery.getScript
768 script
.onload
= script
.onreadystatechange = function() {
773 || this.readyState
=== "loaded"
774 || this.readyState
=== "complete"
779 // Handle memory leak in IE
780 script
.onload
= script
.onreadystatechange
= null;
781 if ( script
.parentNode
) {
782 script
.parentNode
.removeChild( script
);
787 document
.body
.appendChild( script
);
789 document
.write( mw
.html
.element(
790 'script', { 'type': 'text/javascript', 'src': src
}, ''
792 if ( $.isFunction( callback
) ) {
793 // Document.write is synchronous, so this is called when it's done
802 * Requests dependencies from server, loading and executing when things when ready.
804 this.work = function() {
805 // Appends a list of modules to the batch
806 for ( var q
= 0; q
< queue
.length
; q
++ ) {
807 // Only request modules which are undefined or registered
808 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
809 // Prevent duplicate entries
810 if ( $.inArray( queue
[q
], batch
) === -1 ) {
811 batch
[batch
.length
] = queue
[q
];
812 // Mark registered modules as loading
813 if ( queue
[q
] in registry
) {
814 registry
[queue
[q
]].state
= 'loading';
819 // Early exit if there's nothing to load
820 if ( !batch
.length
) {
823 // Clean up the queue
825 // Always order modules alphabetically to help reduce cache
826 // misses for otherwise identical content
828 // Build a list of request parameters
830 'skin': mw
.config
.get( 'skin' ),
831 'lang': mw
.config
.get( 'wgUserLanguage' ),
832 'debug': mw
.config
.get( 'debug' )
834 // Extend request parameters with a list of modules in the batch
838 for ( var b
= 0; b
< batch
.length
; b
++ ) {
839 var group
= registry
[batch
[b
]].group
;
840 if ( !( group
in groups
) ) {
843 groups
[group
][groups
[group
].length
] = batch
[b
];
845 for ( var group
in groups
) {
846 // Calculate the highest timestamp
848 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
849 if ( registry
[groups
[group
][g
]].version
> version
) {
850 version
= registry
[groups
[group
][g
]].version
;
853 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
);
854 var reqBaseLength
= $.param( reqBase
).length
;
856 var limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
857 // We may need to split up the request to honor the query string length limit
858 // So build it piece by piece
859 var l
= reqBaseLength
+ 9; // '&modules='.length == 9
861 reqs
[0] = {}; // { prefix: [ suffixes ] }
862 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
863 // Determine how many bytes this module would add to the query string
864 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' );
865 // Note that these substr() calls work even if lastDotIndex == -1
866 var prefix
= groups
[group
][i
].substr( 0, lastDotIndex
);
867 var suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 );
868 var bytesAdded
= prefix
in reqs
[r
] ?
869 suffix
.length
+ 3 : // '%2C'.length == 3
870 groups
[group
][i
].length
+ 3; // '%7C'.length == 3
872 // If the request would become too long, create a new one,
873 // but don't create empty requests
874 if ( limit
> 0 && reqs
[r
] != {} && l
+ bytesAdded
> limit
) {
875 // This request would become too long, create a new one
878 l
= reqBaseLength
+ 9;
880 if ( !( prefix
in reqs
[r
] ) ) {
881 reqs
[r
][prefix
] = [];
883 reqs
[r
][prefix
].push( suffix
);
886 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
887 requests
[requests
.length
] = $.extend(
888 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
892 // Clear the batch - this MUST happen before we append the
893 // script element to the body or it's possible that the script
894 // will be locally cached, instantly load, and work the batch
895 // again, all before we've cleared it causing each request to
896 // include modules which are already loaded
898 // Asynchronously append a script tag to the end of the body
899 for ( var r
= 0; r
< requests
.length
; r
++ ) {
900 requests
[r
] = sortQuery( requests
[r
] );
901 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
907 * Registers a module, letting the system know about it and its
908 * dependencies. loader.js files contain calls to this function.
910 this.register = function( module
, version
, dependencies
, group
) {
911 // Allow multiple registration
912 if ( typeof module
=== 'object' ) {
913 for ( var m
= 0; m
< module
.length
; m
++ ) {
914 if ( typeof module
[m
] === 'string' ) {
915 mw
.loader
.register( module
[m
] );
916 } else if ( typeof module
[m
] === 'object' ) {
917 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
923 if ( typeof module
!== 'string' ) {
924 throw new Error( 'module must be a string, not a ' + typeof module
);
926 if ( typeof registry
[module
] !== 'undefined' ) {
927 throw new Error( 'module already implemented: ' + module
);
929 // List the module as registered
931 'state': 'registered',
932 'group': typeof group
=== 'string' ? group
: null,
934 'version': typeof version
!== 'undefined' ? parseInt( version
, 10 ) : 0
936 if ( typeof dependencies
=== 'string' ) {
937 // Allow dependencies to be given as a single module name
938 registry
[module
].dependencies
= [dependencies
];
939 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
940 // Allow dependencies to be given as an array of module names
941 // or a function which returns an array
942 registry
[module
].dependencies
= dependencies
;
947 * Implements a module, giving the system a course of action to take
948 * upon loading. Results of a request for one or more modules contain
949 * calls to this function.
951 * All arguments are required.
953 * @param module String: Name of module
954 * @param script Mixed: Function of module code or String of URL to be used as the src
955 * attribute when adding a script element to the body
956 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
957 * keyed by media-type
958 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
960 this.implement = function( module
, script
, style
, msgs
) {
962 if ( typeof module
!== 'string' ) {
963 throw new Error( 'module must be a string, not a ' + typeof module
);
965 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
966 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
968 if ( !$.isPlainObject( style
) ) {
969 throw new Error( 'style must be an object, not a ' + typeof style
);
971 if ( !$.isPlainObject( msgs
) ) {
972 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
974 // Automatically register module
975 if ( typeof registry
[module
] === 'undefined' ) {
976 mw
.loader
.register( module
);
978 // Check for duplicate implementation
979 if ( typeof registry
[module
] !== 'undefined'
980 && typeof registry
[module
].script
!== 'undefined' )
982 throw new Error( 'module already implemeneted: ' + module
);
984 // Mark module as loaded
985 registry
[module
].state
= 'loaded';
987 registry
[module
].script
= script
;
988 registry
[module
].style
= style
;
989 registry
[module
].messages
= msgs
;
990 // Execute or queue callback
992 filter( ['ready'], registry
[module
].dependencies
),
993 registry
[module
].dependencies
) )
1002 * Executes a function as soon as one or more required modules are ready
1004 * @param dependencies string or array of strings of modules names the callback
1005 * dependencies to be ready before
1007 * @param ready function callback to execute when all dependencies are ready (optional)
1008 * @param error function callback to execute when if dependencies have a errors (optional)
1010 this.using = function( dependencies
, ready
, error
) {
1012 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
1013 throw new Error( 'dependencies must be a string or an array, not a ' +
1014 typeof dependencies
);
1016 // Allow calling with a single dependency as a string
1017 if ( typeof dependencies
=== 'string' ) {
1018 dependencies
= [dependencies
];
1020 // Resolve entire dependency map
1021 dependencies
= resolve( dependencies
);
1022 // If all dependencies are met, execute ready immediately
1023 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1024 if ( $.isFunction( ready
) ) {
1028 // If any dependencies have errors execute error immediately
1029 else if ( filter( ['error'], dependencies
).length
) {
1030 if ( $.isFunction( error
) ) {
1034 // Since some dependencies are not yet ready, queue up a request
1036 request( dependencies
, ready
, error
);
1041 * Loads an external script or one or more modules for future use
1043 * @param modules mixed either the name of a module, array of modules,
1044 * or a URL of an external script or style
1045 * @param type string mime-type to use if calling with a URL of an
1046 * external script or style; acceptable values are "text/css" and
1047 * "text/javascript"; if no type is provided, text/javascript is
1050 this.load = function( modules
, type
) {
1052 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1053 throw new Error( 'modules must be a string or an array, not a ' +
1056 // Allow calling with an external script or single dependency as a string
1057 if ( typeof modules
=== 'string' ) {
1058 // Support adding arbitrary external scripts
1059 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
1060 if ( type
=== 'text/css' ) {
1061 $( 'head' ).append( $( '<link />', {
1067 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
1068 addScript( modules
);
1074 // Called with single module
1075 modules
= [modules
];
1077 // Resolve entire dependency map
1078 modules
= resolve( modules
);
1079 // If all modules are ready, nothing dependency be done
1080 if ( compare( filter( ['ready'], modules
), modules
) ) {
1083 // If any modules have errors return false
1084 else if ( filter( ['error'], modules
).length
) {
1087 // Since some modules are not yet ready, queue up a request
1095 * Changes the state of a module
1097 * @param module string module name or object of module name/state pairs
1098 * @param state string state name
1100 this.state = function( module
, state
) {
1101 if ( typeof module
=== 'object' ) {
1102 for ( var m
in module
) {
1103 mw
.loader
.state( m
, module
[m
] );
1107 if ( !( module
in registry
) ) {
1108 mw
.loader
.register( module
);
1110 registry
[module
].state
= state
;
1114 * Gets the version of a module
1116 * @param module string name of module to get version for
1118 this.getVersion = function( module
) {
1119 if ( module
in registry
&& 'version' in registry
[module
] ) {
1120 return formatVersionNumber( registry
[module
].version
);
1125 * @deprecated use mw.loader.getVersion() instead
1127 this.version = function() {
1128 return mediaWiki
.loader
.getVersion
.apply( mediaWiki
.loader
, arguments
);
1132 * Gets the state of a module
1134 * @param module string name of module to get state for
1136 this.getState = function( module
) {
1137 if ( module
in registry
&& 'state' in registry
[module
] ) {
1138 return registry
[module
].state
;
1143 /* Cache document ready status */
1145 $(document
).ready( function() { ready
= true; } );
1148 /** HTML construction helper functions */
1149 this.html
= new ( function () {
1150 var escapeCallback = function( s
) {
1166 * Escape a string for HTML. Converts special characters to HTML entities.
1167 * @param s The string to escape
1169 this.escape = function( s
) {
1170 return s
.replace( /['"<>&]/g, escapeCallback
);
1174 * Wrapper object for raw HTML passed to mw.html.element().
1176 this.Raw = function( value
) {
1181 * Wrapper object for CDATA element contents passed to mw.html.element()
1183 this.Cdata = function( value
) {
1188 * Create an HTML element string, with safe escaping.
1190 * @param name The tag name.
1191 * @param attrs An object with members mapping element names to values
1192 * @param contents The contents of the element. May be either:
1193 * - string: The string is escaped.
1194 * - null or undefined: The short closing form is used, e.g. <br/>.
1195 * - this.Raw: The value attribute is included without escaping.
1196 * - this.Cdata: The value attribute is included, and an exception is
1197 * thrown if it contains an illegal ETAGO delimiter.
1198 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1202 * return h.element( 'div', {},
1203 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1204 * Returns <div><img src="<"/></div>
1206 this.element = function( name
, attrs
, contents
) {
1208 for ( var attrName
in attrs
) {
1209 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1211 if ( typeof contents
== 'undefined' || contents
=== null ) {
1218 if ( typeof contents
=== 'string') {
1220 s
+= this.escape( contents
);
1221 } else if ( contents
instanceof this.Raw
) {
1222 // Raw HTML inclusion
1223 s
+= contents
.value
;
1224 } else if ( contents
instanceof this.Cdata
) {
1226 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1227 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1229 s
+= contents
.value
;
1231 throw new Error( 'mw.html.element: Invalid type of contents' );
1233 s
+= '</' + name
+ '>';
1238 /* Extension points */
1244 // Alias $j to jQuery for backwards compatibility
1246 window
.mw
= mediaWiki
;
1248 /* Auto-register from pre-loaded startup scripts */
1250 if ( $.isFunction( startUp
) ) {