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, str
.length
);
16 escapeRE : function( str
) {
17 return str
.replace ( /([\\{}()\|.?*+-^$\[\]])/g, "\\$1" );
19 // $.isDomElement( document.getElementById('content') ) === true
20 // $.isDomElement( document.getElementsByClassName('portal') ) === false (array)
21 // $.isDomElement( document.getElementsByClassName('portal')[0] ) === true
22 // $.isDomElement( $('#content') ) === false (jQuery object)
23 // $.isDomElement( $('#content').get(0) ) === true
24 // $.isDomElement( 'hello world' ) === false
25 isDomElement : function( el
) {
28 isEmpty : function( v
) {
30 if ( v
=== "" || v
=== 0 || v
=== "0" || v
=== null
31 || v
=== false || typeof v
=== 'undefined' )
35 // the for-loop could potentially contain prototypes
36 // to avoid that we check it's length first
37 if ( v
.length
=== 0 ) {
40 if ( typeof v
=== 'object' ) {
48 compareArray : function( arrThis
, arrAgainst
) {
49 if ( arrThis
.length
!= arrAgainst
.length
) {
52 for ( var i
= 0; i
< arrThis
.length
; i
++ ) {
53 if ( arrThis
[i
] instanceof Array
) {
54 if ( !$.compareArray( arrThis
[i
], arrAgainst
[i
] ) ) {
57 } else if ( arrThis
[i
] !== arrAgainst
[i
] ) {
63 compareObject : function( objectA
, objectB
) {
65 // Do a simple check if the types match
66 if ( typeof( objectA
) == typeof( objectB
) ) {
68 // Only loop over the contents if it really is an object
69 if ( typeof( objectA
) == 'object' ) {
70 // If they are aliases of the same object (ie. mw and mediaWiki) return now
71 if ( objectA
=== objectB
) {
74 // Iterate over each property
75 for ( var prop
in objectA
) {
76 // Check if this property is also present in the other object
77 if ( prop
in objectB
) {
78 // Compare the types of the properties
79 var type
= typeof( objectA
[prop
] );
80 if ( type
== typeof( objectB
[prop
] ) ) {
81 // Recursively check objects inside this one
84 if ( !$.compareObject( objectA
[prop
], objectB
[prop
] ) ) {
89 // Functions need to be strings to compare them properly
90 if ( objectA
[prop
].toString() !== objectB
[prop
].toString() ) {
96 if ( objectA
[prop
] !== objectB
[prop
] ) {
108 // Check for properties in B but not in A
109 // This is about 15% faster (tested in Safari 5 and Firefox 3.6)
110 // ...than incrementing a count variable in the above and below loops
111 // See also: http://www.mediawiki.org/wiki/ResourceLoader/Default_modules/compareObject_test#Results
112 for ( var prop
in objectB
) {
113 if ( !( prop
in objectA
) ) {
127 * Core MediaWiki JavaScript Library
131 window
.mediaWiki
= new ( function( $ ) {
135 // This will not change until we are 100% ready to turn off legacy globals
136 var LEGACY_GLOBALS
= true;
138 /* Private Members */
140 // List of messages that have been requested to be loaded
141 var messageQueue
= {};
146 * An object which allows single and multiple get/set/exists functionality
147 * on a list of key / value pairs.
149 * @param {boolean} global Whether to get/set/exists values on the window
150 * object or a private object
152 function Map( global
) {
153 this.values
= ( global
=== true ) ? window
: {};
157 * Gets the value of a key, or a list of key/value pairs for an array of keys.
159 * If called with no arguments, all values will be returned.
161 * @param selection mixed Key or array of keys to get values for
162 * @param fallback mixed Value to use in case key(s) do not exist (optional)
164 Map
.prototype.get = function( selection
, fallback
) {
165 if ( typeof selection
=== 'object' ) {
166 selection
= $.makeArray( selection
);
168 for ( var i
= 0; i
< selection
.length
; i
++ ) {
169 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
172 } else if ( typeof selection
=== 'string' ) {
173 if ( typeof this.values
[selection
] === 'undefined' ) {
174 if ( typeof fallback
!== 'undefined' ) {
179 return this.values
[selection
];
185 * Sets one or multiple key/value pairs.
187 * @param selection mixed Key or object of key/value pairs to set
188 * @param value mixed Value to set (optional, only in use when key is a string)
190 Map
.prototype.set = function( selection
, value
) {
191 if ( typeof selection
=== 'object' ) {
192 for ( var s
in selection
) {
193 this.values
[s
] = selection
[s
];
195 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
196 this.values
[selection
] = value
;
201 * Checks if one or multiple keys exist.
203 * @param selection mixed Key or array of keys to check
204 * @return boolean Existence of key(s)
206 Map
.prototype.exists = function( selection
) {
207 if ( typeof selection
=== 'object' ) {
208 for ( var s
= 0; s
< selection
.length
; s
++ ) {
209 if ( !( selection
[s
] in this.values
) ) {
215 return selection
in this.values
;
220 * Message object, similar to Message in PHP
222 function Message( map
, key
, parameters
) {
223 this.format
= 'parse';
226 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
230 * Appends parameters for replacement
232 * @param parameters mixed First in a list of variadic arguments to append as message parameters
234 Message
.prototype.params = function( parameters
) {
235 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
236 this.parameters
[this.parameters
.length
] = parameters
[i
];
242 * Converts message object to it's string form based on the state of format
244 * @return {string} String form of message
246 Message
.prototype.toString = function() {
247 if ( !this.map
.exists( this.key
) ) {
248 // Return <key> if key does not exist
249 return '<' + this.key
+ '>';
251 var text
= this.map
.get( this.key
);
252 var parameters
= this.parameters
;
253 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
254 var index
= parseInt( match
, 10 ) - 1;
255 return index
in parameters
? parameters
[index
] : '$' + match
;
257 /* This should be fixed up when we have a parser
258 if ( this.format === 'parse' && 'language' in mediaWiki ) {
259 text = mediaWiki.language.parse( text );
266 * Changes format to parse and converts message to string
268 * @return {string} String form of parsed message
270 Message
.prototype.parse = function() {
271 this.format
= 'parse';
272 return this.toString();
276 * Changes format to plain and converts message to string
278 * @return {string} String form of plain message
280 Message
.prototype.plain = function() {
281 this.format
= 'plain';
282 return this.toString();
286 * Checks if message exists
288 * @return {string} String form of parsed message
290 Message
.prototype.exists = function() {
291 return this.map
.exists( this.key
);
299 /* Private Members */
305 this.options
= new Map();
310 * Generates a random user session ID (32 alpha-numeric characters).
312 * This information would potentially be stored in a cookie to identify a user during a
313 * session or series of sessions. It's uniqueness should not be depended on.
315 * @return string random set of 32 alpha-numeric characters
317 function generateId() {
319 var seed
= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
320 for ( var i
= 0, r
; i
< 32; i
++ ) {
321 r
= Math
.floor( Math
.random() * seed
.length
);
322 id
+= seed
.substring( r
, r
+ 1 );
328 * Gets the current user's name.
330 * @return mixed user name string or null if users is anonymous
332 this.name = function() {
333 return mediaWiki
.config
.get( 'wgUserName' );
337 * Checks if the current user is anonymous.
341 this.anonymous = function() {
342 return that
.name() ? false : true;
346 * Gets a random session ID automatically generated and kept in a cookie.
348 * This ID is ephemeral for everyone, staying in their browser only until they close
351 * Do not use this method before the first call to mw.loader.go(), it depends on
352 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
353 * won't be loaded until the first call to go().
355 * @return string user name or random session ID
357 this.sessionId = function () {
358 var sessionId
= $.cookie( 'mediaWiki.user.sessionId' );
359 if ( typeof sessionId
== 'undefined' || sessionId
== null ) {
360 sessionId
= generateId();
361 $.cookie( 'mediaWiki.user.sessionId', sessionId
, { 'expires': null, 'path': '/' } );
367 * Gets the current user's name or a random ID automatically generated and kept in a cookie.
369 * This ID is persistent for anonymous users, staying in their browser up to 1 year. The
370 * expiration time is reset each time the ID is queried, so in most cases this ID will
371 * persist until the browser's cookies are cleared or the user doesn't visit for 1 year.
373 * Do not use this method before the first call to mw.loader.go(), it depends on
374 * jquery.cookie, which is added to the first pay-load just after mediaWiki is defined, but
375 * won't be loaded until the first call to go().
377 * @return string user name or random session ID
379 this.id = function() {
380 var name
= that
.name();
384 var id
= $.cookie( 'mediaWiki.user.id' );
385 if ( typeof id
== 'undefined' || id
== null ) {
388 // Set cookie if not set, or renew it if already set
389 $.cookie( 'mediaWiki.user.id', id
, { 'expires': 365, 'path': '/' } );
397 * Dummy function which in debug mode can be replaced with a function that
398 * does something clever
400 this.log = function() { };
403 * Make the Map-class publicly available
408 * List of configuration values
410 * In legacy mode the values this object wraps will be in the global space
412 this.config
= new this.Map( LEGACY_GLOBALS
);
415 * Information about the current user
417 this.user
= new User();
420 * Localization system
422 this.messages
= new this.Map();
427 * Gets a message object, similar to wfMessage()
429 * @param key string Key of message to get
430 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
433 this.message = function( key
, parameters
) {
434 // Support variadic arguments
435 if ( typeof parameters
!== 'undefined' ) {
436 parameters
= $.makeArray( arguments
);
441 return new Message( mediaWiki
.messages
, key
, parameters
);
445 * Gets a message string, similar to wfMsg()
447 * @param key string Key of message to get
448 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
451 this.msg = function( key
, parameters
) {
452 return mediaWiki
.message
.apply( mediaWiki
.message
, arguments
).toString();
456 * Client-side module loader which integrates with the MediaWiki ResourceLoader
458 this.loader
= new ( function() {
460 /* Private Members */
463 * Mapping of registered modules
465 * The jquery module is pre-registered, because it must have already
466 * been provided for this object to have been built, and in debug mode
467 * jquery would have been provided through a unique loader request,
468 * making it impossible to hold back registration of jquery until after
474 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
475 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
476 * 'script': function() {},
477 * 'style': 'css code string',
478 * 'messages': { 'key': 'value' },
479 * 'version': ############## (unix timestamp)
484 // List of modules which will be loaded as when ready
486 // List of modules to be loaded
488 // List of callback functions waiting for modules to be ready to be called
490 // Flag indicating that requests should be suspended
491 var suspended
= true;
492 // Flag inidicating that document ready has occured
494 // Marker element for adding dynamic styles
495 var $marker
= $( 'head meta[name=ResourceLoaderDynamicStyles]' );
497 /* Private Methods */
499 function compare( a
, b
) {
500 if ( a
.length
!= b
.length
) {
503 for ( var i
= 0; i
< b
.length
; i
++ ) {
504 if ( $.isArray( a
[i
] ) ) {
505 if ( !compare( a
[i
], b
[i
] ) ) {
509 if ( a
[i
] !== b
[i
] ) {
517 * Generates an ISO8601 "basic" string from a UNIX timestamp
519 function formatVersionNumber( timestamp
) {
520 function pad( a
, b
, c
) {
521 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
524 d
.setTime( timestamp
* 1000 );
526 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
527 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
532 * Recursively resolves dependencies and detects circular references
534 function recurse( module
, resolved
, unresolved
) {
535 if ( typeof registry
[module
] === 'undefined' ) {
536 throw new Error( 'Unknown dependency: ' + module
);
538 // Resolves dynamic loader function and replaces it with its own results
539 if ( typeof registry
[module
].dependencies
=== 'function' ) {
540 registry
[module
].dependencies
= registry
[module
].dependencies();
541 // Ensures the module's dependencies are always in an array
542 if ( typeof registry
[module
].dependencies
!== 'object' ) {
543 registry
[module
].dependencies
= [registry
[module
].dependencies
];
546 // Tracks down dependencies
547 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
548 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
549 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
551 'Circular reference detected: ' + module
+
552 ' -> ' + registry
[module
].dependencies
[n
]
555 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
558 resolved
[resolved
.length
] = module
;
559 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
563 * Gets a list of module names that a module depends on in their proper dependency order
565 * @param module string module name or array of string module names
566 * @return list of dependencies
567 * @throws Error if circular reference is detected
569 function resolve( module
, resolved
, unresolved
) {
570 // Allow calling with an array of module names
571 if ( typeof module
=== 'object' ) {
573 for ( var m
= 0; m
< module
.length
; m
++ ) {
574 var dependencies
= resolve( module
[m
] );
575 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
576 modules
[modules
.length
] = dependencies
[n
];
580 } else if ( typeof module
=== 'string' ) {
581 // Undefined modules have no dependencies
582 if ( !( module
in registry
) ) {
586 recurse( module
, resolved
, [] );
589 throw new Error( 'Invalid module argument: ' + module
);
593 * Narrows a list of module names down to those matching a specific
594 * state. Possible states are 'undefined', 'registered', 'loading',
595 * 'loaded', or 'ready'
597 * @param states string or array of strings of module states to filter by
598 * @param modules array list of module names to filter (optional, all modules
599 * will be used by default)
600 * @return array list of filtered module names
602 function filter( states
, modules
) {
603 // Allow states to be given as a string
604 if ( typeof states
=== 'string' ) {
607 // If called without a list of modules, build and use a list of all modules
609 if ( typeof modules
=== 'undefined' ) {
611 for ( module
in registry
) {
612 modules
[modules
.length
] = module
;
615 // Build a list of modules which are in one of the specified states
616 for ( var s
= 0; s
< states
.length
; s
++ ) {
617 for ( var m
= 0; m
< modules
.length
; m
++ ) {
618 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
619 // Module does not exist
620 if ( states
[s
] == 'undefined' ) {
622 list
[list
.length
] = modules
[m
];
625 // Module exists, check state
626 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
628 list
[list
.length
] = modules
[m
];
637 * Executes a loaded module, making it ready to use
639 * @param module string module name to execute
641 function execute( module
) {
642 if ( typeof registry
[module
] === 'undefined' ) {
643 throw new Error( 'Module has not been registered yet: ' + module
);
644 } else if ( registry
[module
].state
=== 'registered' ) {
645 throw new Error( 'Module has not been requested from the server yet: ' + module
);
646 } else if ( registry
[module
].state
=== 'loading' ) {
647 throw new Error( 'Module has not completed loading yet: ' + module
);
648 } else if ( registry
[module
].state
=== 'ready' ) {
649 throw new Error( 'Module has already been loaded: ' + module
);
651 // Add style sheet to document
652 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
653 $marker
.before( mediaWiki
.html
.element( 'style',
654 { type
: 'text/css' },
655 new mediaWiki
.html
.Cdata( registry
[module
].style
)
657 } else if ( typeof registry
[module
].style
=== 'object'
658 && !( registry
[module
].style
instanceof Array
) )
660 for ( var media
in registry
[module
].style
) {
661 $marker
.before( mediaWiki
.html
.element( 'style',
662 { type
: 'text/css', media
: media
},
663 new mediaWiki
.html
.Cdata( registry
[module
].style
[media
] )
667 // Add localizations to message system
668 if ( typeof registry
[module
].messages
=== 'object' ) {
669 mediaWiki
.messages
.set( registry
[module
].messages
);
673 registry
[module
].script( jQuery
);
674 registry
[module
].state
= 'ready';
675 // Run jobs who's dependencies have just been met
676 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
678 filter( 'ready', jobs
[j
].dependencies
),
679 jobs
[j
].dependencies
) )
681 if ( typeof jobs
[j
].ready
=== 'function' ) {
688 // Execute modules who's dependencies have just been met
689 for ( r
in registry
) {
690 if ( registry
[r
].state
== 'loaded' ) {
692 filter( ['ready'], registry
[r
].dependencies
),
693 registry
[r
].dependencies
) )
700 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
702 registry
[module
].state
= 'error';
703 // Run error callbacks of jobs affected by this condition
704 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
705 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
706 if ( typeof jobs
[j
].error
=== 'function' ) {
717 * Adds a dependencies to the queue with optional callbacks to be run
718 * when the dependencies are ready or fail
720 * @param dependencies string module name or array of string module names
721 * @param ready function callback to execute when all dependencies are ready
722 * @param error function callback to execute when any dependency fails
724 function request( dependencies
, ready
, error
) {
725 // Allow calling by single module name
726 if ( typeof dependencies
=== 'string' ) {
727 dependencies
= [dependencies
];
728 if ( dependencies
[0] in registry
) {
729 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
730 dependencies
[dependencies
.length
] =
731 registry
[dependencies
[0]].dependencies
[n
];
735 // Add ready and error callbacks if they were given
736 if ( arguments
.length
> 1 ) {
737 jobs
[jobs
.length
] = {
738 'dependencies': filter(
739 ['undefined', 'registered', 'loading', 'loaded'],
745 // Queue up any dependencies that are undefined or registered
746 dependencies
= filter( ['undefined', 'registered'], dependencies
);
747 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
748 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
749 queue
[queue
.length
] = dependencies
[n
];
753 mediaWiki
.loader
.work();
756 function sortQuery(o
) {
757 var sorted
= {}, key
, a
= [];
759 if ( o
.hasOwnProperty( key
) ) {
764 for ( key
= 0; key
< a
.length
; key
++ ) {
765 sorted
[a
[key
]] = o
[a
[key
]];
773 * Requests dependencies from server, loading and executing when things when ready.
775 this.work = function() {
776 // Appends a list of modules to the batch
777 for ( var q
= 0; q
< queue
.length
; q
++ ) {
778 // Only request modules which are undefined or registered
779 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
780 // Prevent duplicate entries
781 if ( $.inArray( queue
[q
], batch
) === -1 ) {
782 batch
[batch
.length
] = queue
[q
];
783 // Mark registered modules as loading
784 if ( queue
[q
] in registry
) {
785 registry
[queue
[q
]].state
= 'loading';
790 // Clean up the queue
792 // After document ready, handle the batch
793 if ( !suspended
&& batch
.length
) {
794 // Always order modules alphabetically to help reduce cache
795 // misses for otherwise identical content
797 // Build a list of request parameters
799 'skin': mediaWiki
.config
.get( 'skin' ),
800 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
801 'debug': mediaWiki
.config
.get( 'debug' )
803 // Extend request parameters with a list of modules in the batch
807 for ( var b
= 0; b
< batch
.length
; b
++ ) {
808 var group
= registry
[batch
[b
]].group
;
809 if ( !( group
in groups
) ) {
812 groups
[group
][groups
[group
].length
] = batch
[b
];
814 for ( var group
in groups
) {
815 // Calculate the highest timestamp
817 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
818 if ( registry
[groups
[group
][g
]].version
> version
) {
819 version
= registry
[groups
[group
][g
]].version
;
822 requests
[requests
.length
] = $.extend(
823 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
826 // Clear the batch - this MUST happen before we append the
827 // script element to the body or it's possible that the script
828 // will be locally cached, instantly load, and work the batch
829 // again, all before we've cleared it causing each request to
830 // include modules which are already loaded
832 // Asynchronously append a script tag to the end of the body
835 for ( var r
= 0; r
< requests
.length
; r
++ ) {
836 requests
[r
] = sortQuery( requests
[r
] );
837 // Build out the HTML
838 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
839 html
+= mediaWiki
.html
.element( 'script',
840 { type
: 'text/javascript', src
: src
}, '' );
844 // Load asynchronously after documument ready
846 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
848 document
.write( request() );
854 * Registers a module, letting the system know about it and its
855 * dependencies. loader.js files contain calls to this function.
857 this.register = function( module
, version
, dependencies
, group
) {
858 // Allow multiple registration
859 if ( typeof module
=== 'object' ) {
860 for ( var m
= 0; m
< module
.length
; m
++ ) {
861 if ( typeof module
[m
] === 'string' ) {
862 mediaWiki
.loader
.register( module
[m
] );
863 } else if ( typeof module
[m
] === 'object' ) {
864 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
870 if ( typeof module
!== 'string' ) {
871 throw new Error( 'module must be a string, not a ' + typeof module
);
873 if ( typeof registry
[module
] !== 'undefined' ) {
874 throw new Error( 'module already implemeneted: ' + module
);
876 // List the module as registered
878 'state': 'registered',
879 'group': typeof group
=== 'string' ? group
: null,
881 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
883 if ( typeof dependencies
=== 'string' ) {
884 // Allow dependencies to be given as a single module name
885 registry
[module
].dependencies
= [dependencies
];
886 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
887 // Allow dependencies to be given as an array of module names
888 // or a function which returns an array
889 registry
[module
].dependencies
= dependencies
;
894 * Implements a module, giving the system a course of action to take
895 * upon loading. Results of a request for one or more modules contain
896 * calls to this function.
898 this.implement = function( module
, script
, style
, localization
) {
899 // Automatically register module
900 if ( typeof registry
[module
] === 'undefined' ) {
901 mediaWiki
.loader
.register( module
);
904 if ( typeof script
!== 'function' ) {
905 throw new Error( 'script must be a function, not a ' + typeof script
);
907 if ( typeof style
!== 'undefined'
908 && typeof style
!== 'string'
909 && typeof style
!== 'object' )
911 throw new Error( 'style must be a string or object, not a ' + typeof style
);
913 if ( typeof localization
!== 'undefined'
914 && typeof localization
!== 'object' )
916 throw new Error( 'localization must be an object, not a ' + typeof localization
);
918 if ( typeof registry
[module
] !== 'undefined'
919 && typeof registry
[module
].script
!== 'undefined' )
921 throw new Error( 'module already implemeneted: ' + module
);
923 // Mark module as loaded
924 registry
[module
].state
= 'loaded';
926 registry
[module
].script
= script
;
927 if ( typeof style
=== 'string'
928 || typeof style
=== 'object' && !( style
instanceof Array
) )
930 registry
[module
].style
= style
;
932 if ( typeof localization
=== 'object' ) {
933 registry
[module
].messages
= localization
;
935 // Execute or queue callback
937 filter( ['ready'], registry
[module
].dependencies
),
938 registry
[module
].dependencies
) )
947 * Executes a function as soon as one or more required modules are ready
949 * @param dependencies string or array of strings of modules names the callback
950 * dependencies to be ready before
952 * @param ready function callback to execute when all dependencies are ready (optional)
953 * @param error function callback to execute when if dependencies have a errors (optional)
955 this.using = function( dependencies
, ready
, error
) {
957 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
958 throw new Error( 'dependencies must be a string or an array, not a ' +
959 typeof dependencies
)
961 // Allow calling with a single dependency as a string
962 if ( typeof dependencies
=== 'string' ) {
963 dependencies
= [dependencies
];
965 // Resolve entire dependency map
966 dependencies
= resolve( dependencies
);
967 // If all dependencies are met, execute ready immediately
968 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
969 if ( typeof ready
=== 'function' ) {
973 // If any dependencies have errors execute error immediately
974 else if ( filter( ['error'], dependencies
).length
) {
975 if ( typeof error
=== 'function' ) {
979 // Since some dependencies are not yet ready, queue up a request
981 request( dependencies
, ready
, error
);
986 * Loads an external script or one or more modules for future use
988 * @param modules mixed either the name of a module, array of modules,
989 * or a URL of an external script or style
990 * @param type string mime-type to use if calling with a URL of an
991 * external script or style; acceptable values are "text/css" and
992 * "text/javascript"; if no type is provided, text/javascript is
995 this.load = function( modules
, type
) {
997 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
998 throw new Error( 'dependencies must be a string or an array, not a ' +
999 typeof dependencies
)
1001 // Allow calling with an external script or single dependency as a string
1002 if ( typeof modules
=== 'string' ) {
1003 // Support adding arbitrary external scripts
1004 if ( modules
.substr( 0, 7 ) == 'http://'
1005 || modules
.substr( 0, 8 ) == 'https://' )
1007 if ( type
=== 'text/css' ) {
1009 .append( $( '<link rel="stylesheet" type="text/css" />' )
1010 .attr( 'href', modules
) );
1012 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
1013 var script
= mediaWiki
.html
.element( 'script',
1014 { type
: 'text/javascript', src
: modules
}, '' );
1016 $( 'body' ).append( script
);
1018 document
.write( script
);
1025 // Called with single module
1026 modules
= [modules
];
1028 // Resolve entire dependency map
1029 modules
= resolve( modules
);
1030 // If all modules are ready, nothing dependency be done
1031 if ( compare( filter( ['ready'], modules
), modules
) ) {
1034 // If any modules have errors return false
1035 else if ( filter( ['error'], modules
).length
) {
1038 // Since some modules are not yet ready, queue up a request
1046 * Flushes the request queue and begin executing load requests on demand
1048 this.go = function() {
1050 mediaWiki
.loader
.work();
1054 * Changes the state of a module
1056 * @param module string module name or object of module name/state pairs
1057 * @param state string state name
1059 this.state = function( module
, state
) {
1060 if ( typeof module
=== 'object' ) {
1061 for ( var m
in module
) {
1062 mediaWiki
.loader
.state( m
, module
[m
] );
1066 if ( !( module
in registry
) ) {
1067 mediaWiki
.loader
.register( module
);
1069 registry
[module
].state
= state
;
1073 * Gets the version of a module
1075 * @param module string name of module to get version for
1077 this.version = function( module
) {
1078 if ( module
in registry
&& 'version' in registry
[module
] ) {
1079 return formatVersionNumber( registry
[module
].version
);
1084 /* Cache document ready status */
1086 $(document
).ready( function() { ready
= true; } );
1089 /** HTML construction helper functions */
1090 this.html
= new ( function () {
1091 function escapeCallback( s
) {
1107 * Escape a string for HTML. Converts special characters to HTML entities.
1108 * @param s The string to escape
1110 this.escape = function( s
) {
1111 return s
.replace( /['"<>&]/g, escapeCallback
);
1115 * Wrapper object for raw HTML passed to mw.html.element().
1117 this.Raw = function( value
) {
1122 * Wrapper object for CDATA element contents passed to mw.html.element()
1124 this.Cdata = function( value
) {
1129 * Create an HTML element string, with safe escaping.
1131 * @param name The tag name.
1132 * @param attrs An object with members mapping element names to values
1133 * @param contents The contents of the element. May be either:
1134 * - string: The string is escaped.
1135 * - null or undefined: The short closing form is used, e.g. <br/>.
1136 * - this.Raw: The value attribute is included without escaping.
1137 * - this.Cdata: The value attribute is included, and an exception is
1138 * thrown if it contains an illegal ETAGO delimiter.
1139 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1143 * return h.element( 'div', {},
1144 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1145 * Returns <div><img src="<"/></div>
1147 this.element = function( name
, attrs
, contents
) {
1149 for ( var attrName
in attrs
) {
1150 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1152 if ( typeof contents
== 'undefined' || contents
=== null ) {
1159 if ( typeof contents
=== 'string') {
1161 s
+= this.escape( contents
);
1162 } else if ( contents
instanceof this.Raw
) {
1163 // Raw HTML inclusion
1164 s
+= contents
.value
;
1165 } else if ( contents
instanceof this.Cdata
) {
1167 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1168 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1170 s
+= contents
.value
;
1172 throw new Error( 'mw.html.element: Invalid type of contents' );
1174 s
+= '</' + name
+ '>';
1180 /* Extension points */
1186 /* Auto-register from pre-loaded startup scripts */
1188 if ( typeof startUp
=== 'function' ) {
1193 // Add jQuery Cookie to initial payload (used in mediaWiki.user)
1194 mediaWiki
.loader
.load( 'jquery.cookie' );
1196 // Alias $j to jQuery for backwards compatibility
1198 window
.mw
= mediaWiki
;