2 * JavaScript backwards-compatibility and support
5 // Implementation of string trimming functionality introduced natively in JavaScript 1.8.1
6 if ( typeof String
.prototype.trim
=== 'undefined' ) {
7 // Add removing trailing and leading whitespace functionality cross-browser
8 // See also: http://blog.stevenlevithan.com/archives/faster-trim-javascript
9 String
.prototype.trim = function() {
10 return this.replace( /^\s+|\s+$/g, '' );
13 if ( typeof String
.prototype.trimLeft
=== 'undefined' ) {
14 String
.prototype.trimLeft = function() {
15 return this.replace( /^\s\s*/, "" );
18 if ( typeof String
.prototype.trimRight
=== 'undefined' ) {
19 String
.prototype.trimRight = function() {
20 return this.replace(/\s\s*$/, "");
25 * Core MediaWiki JavaScript Library
29 window
.mediaWiki
= new ( function( $ ) {
33 // This will not change until we are 100% ready to turn off legacy globals
34 var LEGACY_GLOBALS
= true;
38 // List of messages that have been requested to be loaded
39 var messageQueue
= {};
44 * An object which allows single and multiple get/set/exists functionality on a list of key / value pairs.
46 * @param {boolean} global Whether to get/set/exists values on the window object or a private object
48 function Map( global
) {
49 this.values
= ( global
=== true ) ? window
: {};
53 * Gets the value of a key, or a list of key/value pairs for an array of keys.
55 * If called with no arguments, all values will be returned.
57 * @param {mixed} selection Key or array of keys to get values for
58 * @param {mixed} fallback Value to use in case key(s) do not exist (optional)
60 Map
.prototype.get = function( selection
, fallback
) {
61 if ( typeof selection
=== 'object' ) {
62 selection
= $.makeArray( selection
);
64 for ( var i
= 0; i
< selection
.length
; i
++ ) {
65 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
68 } else if ( typeof selection
=== 'string' ) {
69 if ( typeof this.values
[selection
] === 'undefined' ) {
70 if ( typeof fallback
!== 'undefined' ) {
75 return this.values
[selection
];
81 * Sets one or multiple key/value pairs.
83 * @param {mixed} selection Key or object of key/value pairs to set
84 * @param {mixed} value Value to set (optional, only in use when key is a string)
86 Map
.prototype.set = function( selection
, value
) {
87 if ( typeof selection
=== 'object' ) {
88 for ( var s
in selection
) {
89 this.values
[s
] = selection
[s
];
91 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
92 this.values
[selection
] = value
;
97 * Checks if one or multiple keys exist.
99 * @param {mixed} key Key or array of keys to check
100 * @return {boolean} Existence of key(s)
102 Map
.prototype.exists = function( selection
) {
103 if ( typeof keys
=== 'object' ) {
104 for ( var s
= 0; s
< selection
.length
; s
++ ) {
105 if ( !( selection
[s
] in this.values
) ) {
111 return selection
in this.values
;
116 * Message object, similar to Message in PHP
118 function Message( map
, key
, parameters
) {
119 this.format
= 'parse';
122 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
126 * Appends parameters for replacement
128 * @param {mixed} args First in a list of variadic arguments to append as message parameters
130 Message
.prototype.params = function( parameters
) {
131 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
132 this.parameters
[this.parameters
.length
] = parameters
[i
];
138 * Converts message object to it's string form based on the state of format
140 * @return {string} String form of message
142 Message
.prototype.toString = function() {
143 if ( !this.map
.exists( this.key
) ) {
144 // Return <key> if key does not exist
145 return '<' + this.key
+ '>';
147 var text
= this.map
.get( this.key
);
148 var parameters
= this.parameters
;
149 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
150 var index
= parseInt( match
, 10 ) - 1;
151 return index
in parameters
? parameters
[index
] : '$' + match
;
153 /* This should be fixed up when we have a parser
154 if ( this.format === 'parse' && 'language' in mediaWiki ) {
155 text = mediaWiki.language.parse( text );
162 * Changes format to parse and converts message to string
164 * @return {string} String form of parsed message
166 Message
.prototype.parse = function() {
167 this.format
= 'parse';
168 return this.toString();
172 * Changes format to plain and converts message to string
174 * @return {string} String form of plain message
176 Message
.prototype.plain = function() {
177 this.format
= 'plain';
178 return this.toString();
182 * Checks if message exists
184 * @return {string} String form of parsed message
186 Message
.prototype.exists = function() {
187 return this.map
.exists( this.key
);
194 this.options
= new Map();
200 * Dummy function which in debug mode can be replaced with a function that does something clever
202 this.log = function() { };
205 * List of configuration values
207 * In legacy mode the values this object wraps will be in the global space
209 this.config
= new Map( LEGACY_GLOBALS
);
212 * Information about the current user
214 this.user
= new User();
217 * Localization system
219 this.messages
= new Map();
224 * Gets a message object, similar to wfMessage()
226 * @param {string} key Key of message to get
227 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
230 this.message = function( key
, parameters
) {
231 // Support variadic arguments
232 if ( typeof parameters
!== 'undefined' ) {
233 parameters
= $.makeArray( arguments
);
238 return new Message( mediaWiki
.messages
, key
, parameters
);
242 * Gets a message string, similar to wfMsg()
244 * @param {string} key Key of message to get
245 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
248 this.msg = function( key
, parameters
) {
249 return mediaWiki
.message
.apply( mediaWiki
.message
, arguments
).toString();
253 * Client-side module loader which integrates with the MediaWiki ResourceLoader
255 this.loader
= new ( function() {
257 /* Private Members */
260 * Mapping of registered modules
262 * The jquery module is pre-registered, because it must have already been provided for this object to have
263 * been built, and in debug mode jquery would have been provided through a unique loader request, making it
264 * impossible to hold back registration of jquery until after mediawiki.
269 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
270 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
271 * 'script': function() {},
272 * 'style': 'css code string',
273 * 'messages': { 'key': 'value' },
274 * 'version': ############## (unix timestamp)
279 // List of modules which will be loaded as when ready
281 // List of modules to be loaded
283 // List of callback functions waiting for modules to be ready to be called
285 // Flag indicating that requests should be suspended
286 var suspended
= true;
287 // Flag inidicating that document ready has occured
290 /* Private Methods */
292 function compare( a
, b
) {
293 if ( a
.length
!= b
.length
) {
296 for ( var i
= 0; i
< b
.length
; i
++ ) {
297 if ( $.isArray( a
[i
] ) ) {
298 if ( !compare( a
[i
], b
[i
] ) ) {
302 if ( a
[i
] !== b
[i
] ) {
310 * Generates an ISO8601 "basic" string from a UNIX timestamp
312 function formatVersionNumber( timestamp
) {
313 function pad( a
, b
, c
) {
314 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
317 d
.setTime( timestamp
* 1000 );
319 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
320 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
325 * Recursively resolves dependencies and detects circular references
327 function recurse( module
, resolved
, unresolved
) {
328 if ( typeof registry
[module
] === 'undefined' ) {
329 throw new Error( 'Unknown dependency: ' + module
);
331 // Resolves dynamic loader function and replaces it with it's own results
332 if ( typeof registry
[module
].dependencies
=== 'function' ) {
333 registry
[module
].dependencies
= registry
[module
].dependencies();
334 // Ensures the module's dependencies are always in an array
335 if ( typeof registry
[module
].dependencies
!== 'object' ) {
336 registry
[module
].dependencies
= [registry
[module
].dependencies
];
339 // Tracks down dependencies
340 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
341 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
342 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
344 'Circular reference detected: ' + module
+ ' -> ' + registry
[module
].dependencies
[n
]
347 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
350 resolved
[resolved
.length
] = module
;
351 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
355 * Gets a list of modules names that a module dependencies in their proper dependency order
357 * @param mixed string module name or array of string module names
358 * @return list of dependencies
359 * @throws Error if circular reference is detected
361 function resolve( module
, resolved
, unresolved
) {
362 // Allow calling with an array of module names
363 if ( typeof module
=== 'object' ) {
365 for ( var m
= 0; m
< module
.length
; m
++ ) {
366 var dependencies
= resolve( module
[m
] );
367 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
368 modules
[modules
.length
] = dependencies
[n
];
372 } else if ( typeof module
=== 'string' ) {
373 // Undefined modules have no dependencies
374 if ( !( module
in registry
) ) {
378 recurse( module
, resolved
, [] );
381 throw new Error( 'Invalid module argument: ' + module
);
385 * Narrows a list of module names down to those matching a specific state. Possible states are 'undefined',
386 * 'registered', 'loading', 'loaded', or 'ready'
388 * @param mixed string or array of strings of module states to filter by
389 * @param array list of module names to filter (optional, all modules will be used by default)
390 * @return array list of filtered module names
392 function filter( states
, modules
) {
393 // Allow states to be given as a string
394 if ( typeof states
=== 'string' ) {
397 // If called without a list of modules, build and use a list of all modules
399 if ( typeof modules
=== 'undefined' ) {
401 for ( module
in registry
) {
402 modules
[modules
.length
] = module
;
405 // Build a list of modules which are in one of the specified states
406 for ( var s
= 0; s
< states
.length
; s
++ ) {
407 for ( var m
= 0; m
< modules
.length
; m
++ ) {
409 ( states
[s
] == 'undefined' && typeof registry
[modules
[m
]] === 'undefined' ) ||
410 ( typeof registry
[modules
[m
]] === 'object' && registry
[modules
[m
]].state
=== states
[s
] )
412 list
[list
.length
] = modules
[m
];
420 * Executes a loaded module, making it ready to use
422 * @param string module name to execute
424 function execute( module
) {
425 if ( typeof registry
[module
] === 'undefined' ) {
426 throw new Error( 'Module has not been registered yet: ' + module
);
427 } else if ( registry
[module
].state
=== 'registered' ) {
428 throw new Error( 'Module has not been requested from the server yet: ' + module
);
429 } else if ( registry
[module
].state
=== 'loading' ) {
430 throw new Error( 'Module has not completed loading yet: ' + module
);
431 } else if ( registry
[module
].state
=== 'ready' ) {
432 throw new Error( 'Module has already been loaded: ' + module
);
434 // Add style sheet to document
435 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
436 $( 'head' ).append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
437 } else if ( typeof registry
[module
].style
=== 'object' && !( registry
[module
].style
instanceof Array
) ) {
438 for ( var media
in registry
[module
].style
) {
440 '<style type="text/css" media="' + media
+ '">' + registry
[module
].style
[media
] + '</style>'
444 // Add localizations to message system
445 if ( typeof registry
[module
].messages
=== 'object' ) {
446 mediaWiki
.messages
.set( registry
[module
].messages
);
450 registry
[module
].script();
451 registry
[module
].state
= 'ready';
452 // Run jobs who's dependencies have just been met
453 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
454 if ( compare( filter( 'ready', jobs
[j
].dependencies
), jobs
[j
].dependencies
) ) {
455 if ( typeof jobs
[j
].ready
=== 'function' ) {
462 // Execute modules who's dependencies have just been met
463 for ( r
in registry
) {
464 if ( registry
[r
].state
== 'loaded' ) {
465 if ( compare( filter( ['ready'], registry
[r
].dependencies
), registry
[r
].dependencies
) ) {
471 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
473 registry
[module
].state
= 'error';
474 // Run error callbacks of jobs affected by this condition
475 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
476 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
477 if ( typeof jobs
[j
].error
=== 'function' ) {
488 * Adds a dependencies to the queue with optional callbacks to be run when the dependencies are ready or fail
490 * @param mixed string moulde name or array of string module names
491 * @param function ready callback to execute when all dependencies are ready
492 * @param function error callback to execute when any dependency fails
494 function request( dependencies
, ready
, error
) {
495 // Allow calling by single module name
496 if ( typeof dependencies
=== 'string' ) {
497 dependencies
= [dependencies
];
498 if ( dependencies
[0] in registry
) {
499 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
500 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
504 // Add ready and error callbacks if they were given
505 if ( arguments
.length
> 1 ) {
506 jobs
[jobs
.length
] = {
507 'dependencies': filter( ['undefined', 'registered', 'loading', 'loaded'], dependencies
),
512 // Queue up any dependencies that are undefined or registered
513 dependencies
= filter( ['undefined', 'registered'], dependencies
);
514 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
515 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
516 queue
[queue
.length
] = dependencies
[n
];
520 mediaWiki
.loader
.work();
523 function sortQuery(o
) {
524 var sorted
= {}, key
, a
= [];
526 if ( o
.hasOwnProperty( key
) ) {
531 for ( key
= 0; key
< a
.length
; key
++ ) {
532 sorted
[a
[key
]] = o
[a
[key
]];
540 * Requests dependencies from server, loading and executing when things when ready.
542 this.work = function() {
543 // Appends a list of modules to the batch
544 for ( var q
= 0; q
< queue
.length
; q
++ ) {
545 // Only request modules which are undefined or registered
546 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
547 // Prevent duplicate entries
548 if ( $.inArray( queue
[q
], batch
) === -1 ) {
549 batch
[batch
.length
] = queue
[q
];
550 // Mark registered modules as loading
551 if ( queue
[q
] in registry
) {
552 registry
[queue
[q
]].state
= 'loading';
557 // Clean up the queue
559 // After document ready, handle the batch
560 if ( !suspended
&& batch
.length
) {
561 // Always order modules alphabetically to help reduce cache misses for otherwise identical content
563 // Build a list of request parameters
565 'skin': mediaWiki
.config
.get( 'skin' ),
566 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
567 'debug': mediaWiki
.config
.get( 'debug' )
569 // Extend request parameters with a list of modules in the batch
573 for ( var b
= 0; b
< batch
.length
; b
++ ) {
574 var group
= registry
[batch
[b
]].group
;
575 if ( !( group
in groups
) ) {
578 groups
[group
][groups
[group
].length
] = batch
[b
];
580 for ( var group
in groups
) {
581 // Calculate the highest timestamp
583 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
584 if ( registry
[groups
[group
][g
]].version
> version
) {
585 version
= registry
[groups
[group
][g
]].version
;
588 requests
[requests
.length
] = $.extend(
589 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
592 // Clear the batch - this MUST happen before we append the script element to the body or it's
593 // possible that the script will be locally cached, instantly load, and work the batch again,
594 // all before we've cleared it causing each request to include modules which are already loaded
596 // Asynchronously append a script tag to the end of the body
599 for ( var r
= 0; r
< requests
.length
; r
++ ) {
600 requests
[r
] = sortQuery( requests
[r
] );
601 // Build out the HTML
602 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
603 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
607 // Load asynchronously after doumument ready
609 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
611 document
.write( request() );
617 * Registers a module, letting the system know about it and it's dependencies. loader.js files contain calls
620 this.register = function( module
, version
, dependencies
, group
) {
621 // Allow multiple registration
622 if ( typeof module
=== 'object' ) {
623 for ( var m
= 0; m
< module
.length
; m
++ ) {
624 if ( typeof module
[m
] === 'string' ) {
625 mediaWiki
.loader
.register( module
[m
] );
626 } else if ( typeof module
[m
] === 'object' ) {
627 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
633 if ( typeof module
!== 'string' ) {
634 throw new Error( 'module must be a string, not a ' + typeof module
);
636 if ( typeof registry
[module
] !== 'undefined' ) {
637 throw new Error( 'module already implemeneted: ' + module
);
639 // List the module as registered
641 'state': 'registered',
642 'group': typeof group
=== 'string' ? group
: null,
644 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
646 if ( typeof dependencies
=== 'string' ) {
647 // Allow dependencies to be given as a single module name
648 registry
[module
].dependencies
= [dependencies
];
649 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
650 // Allow dependencies to be given as an array of module names or a function which returns an array
651 registry
[module
].dependencies
= dependencies
;
656 * Implements a module, giving the system a course of action to take upon loading. Results of a request for
657 * one or more modules contain calls to this function.
659 this.implement = function( module
, script
, style
, localization
) {
660 // Automaically register module
661 if ( typeof registry
[module
] === 'undefined' ) {
662 mediaWiki
.loader
.register( module
);
665 if ( typeof script
!== 'function' ) {
666 throw new Error( 'script must be a function, not a ' + typeof script
);
668 if ( typeof style
!== 'undefined' && typeof style
!== 'string' && typeof style
!== 'object' ) {
669 throw new Error( 'style must be a string or object, not a ' + typeof style
);
671 if ( typeof localization
!== 'undefined' && typeof localization
!== 'object' ) {
672 throw new Error( 'localization must be an object, not a ' + typeof localization
);
674 if ( typeof registry
[module
] !== 'undefined' && typeof registry
[module
].script
!== 'undefined' ) {
675 throw new Error( 'module already implemeneted: ' + module
);
677 // Mark module as loaded
678 registry
[module
].state
= 'loaded';
680 registry
[module
].script
= script
;
681 if ( typeof style
=== 'string' || typeof style
=== 'object' && !( style
instanceof Array
) ) {
682 registry
[module
].style
= style
;
684 if ( typeof localization
=== 'object' ) {
685 registry
[module
].messages
= localization
;
687 // Execute or queue callback
688 if ( compare( filter( ['ready'], registry
[module
].dependencies
), registry
[module
].dependencies
) ) {
696 * Executes a function as soon as one or more required modules are ready
698 * @param mixed string or array of strings of modules names the callback dependencies to be ready before
700 * @param function callback to execute when all dependencies are ready (optional)
701 * @param function callback to execute when if dependencies have a errors (optional)
703 this.using = function( dependencies
, ready
, error
) {
705 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
706 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
708 // Allow calling with a single dependency as a string
709 if ( typeof dependencies
=== 'string' ) {
710 dependencies
= [dependencies
];
712 // Resolve entire dependency map
713 dependencies
= resolve( dependencies
);
714 // If all dependencies are met, execute ready immediately
715 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
716 if ( typeof ready
=== 'function' ) {
720 // If any dependencies have errors execute error immediately
721 else if ( filter( ['error'], dependencies
).length
) {
722 if ( typeof error
=== 'function' ) {
726 // Since some dependencies are not yet ready, queue up a request
728 request( dependencies
, ready
, error
);
733 * Loads an external script or one or more modules for future use
735 * @param {mixed} modules either the name of a module, array of modules, or a URL of an external script or style
736 * @param {string} type mime-type to use if calling with a URL of an external script or style; acceptable values
737 * are "text/css" and "text/javascript"; if no type is provided, text/javascript is assumed
739 this.load = function( modules
, type
) {
741 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
742 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
744 // Allow calling with an external script or single dependency as a string
745 if ( typeof modules
=== 'string' ) {
746 // Support adding arbitrary external scripts
747 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
748 if ( type
=== 'text/css' ) {
749 $( 'head' ).append( $( '<link rel="stylesheet" type="text/css" />' ).attr( 'href', modules
) );
751 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
752 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
754 $( 'body' ).append( script
);
756 document
.write( script
);
763 // Called with single module
766 // Resolve entire dependency map
767 modules
= resolve( modules
);
768 // If all modules are ready, nothing dependency be done
769 if ( compare( filter( ['ready'], modules
), modules
) ) {
772 // If any modules have errors return false
773 else if ( filter( ['error'], modules
).length
) {
776 // Since some modules are not yet ready, queue up a request
784 * Flushes the request queue and begin executing load requests on demand
786 this.go = function() {
788 mediaWiki
.loader
.work();
792 * Changes the state of a module
794 * @param mixed module string module name or object of module name/state pairs
795 * @param string state string state name
797 this.state = function( module
, state
) {
798 if ( typeof module
=== 'object' ) {
799 for ( var m
in module
) {
800 mediaWiki
.loader
.state( m
, module
[m
] );
804 if ( !( module
in registry
) ) {
805 mediaWiki
.loader
.register( module
);
807 registry
[module
].state
= state
;
811 * Gets the version of a module
813 * @param string module name of module to get version for
815 this.version = function( module
) {
816 if ( module
in registry
&& 'version' in registry
[module
] ) {
817 return formatVersionNumber( registry
[module
].version
);
822 /* Cache document ready status */
824 $(document
).ready( function() { ready
= true; } );
827 /* Extension points */
833 /* Auto-register from pre-loaded startup scripts */
835 if ( typeof startUp
=== 'function' ) {
840 // Alias $j to jQuery for backwards compatibility
842 window
.mw
= mediaWiki
;