2 * JavaScript backwards-compatibility and support
5 // New fallback String trimming functionality, was 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*/, "" );
19 if ( typeof String
.prototype.trimRight
=== 'undefined' ) {
20 String
.prototype.trimRight = function() {
21 return this.replace(/\s\s*$/, "");
26 * Core MediaWiki JavaScript Library
30 window
.mediaWiki
= new ( function( $ ) {
34 // This will not change until we are 100% ready to turn off legacy globals
35 var LEGACY_GLOBALS
= true;
39 // List of messages that have been requested to be loaded
40 var messageQueue
= {};
45 * An object which allows single and multiple get/set/exists functionality on a list of key / value pairs.
47 * @param {boolean} global Whether to get/set/exists values on the window object or a private object
49 function Map( global
) {
50 this.values
= ( global
=== true ) ? window
: {};
54 * Gets the value of a key, or a list of key/value pairs for an array of keys.
56 * If called with no arguments, all values will be returned.
58 * @param {mixed} selection Key or array of keys to get values for
59 * @param {mixed} fallback Value to use in case key(s) do not exist (optional)
61 Map
.prototype.get = function( selection
, fallback
) {
62 if ( typeof selection
=== 'object' ) {
63 selection
= $.makeArray( selection
);
65 for ( var i
= 0; i
< selection
.length
; i
++ ) {
66 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
69 } else if ( typeof selection
=== 'string' ) {
70 if ( typeof this.values
[selection
] === 'undefined' ) {
71 if ( typeof fallback
!== 'undefined' ) {
76 return this.values
[selection
];
82 * Sets one or multiple key/value pairs.
84 * @param {mixed} selection Key or object of key/value pairs to set
85 * @param {mixed} value Value to set (optional, only in use when key is a string)
87 Map
.prototype.set = function( selection
, value
) {
88 if ( typeof selection
=== 'object' ) {
89 for ( var s
in selection
) {
90 this.values
[s
] = selection
[s
];
92 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
93 this.values
[selection
] = value
;
98 * Checks if one or multiple keys exist.
100 * @param {mixed} key Key or array of keys to check
101 * @return {boolean} Existence of key(s)
103 Map
.prototype.exists = function( selection
) {
104 if ( typeof keys
=== 'object' ) {
105 for ( var s
= 0; s
< selection
.length
; s
++ ) {
106 if ( !( selection
[s
] in this.values
) ) {
112 return selection
in this.values
;
117 * Message object, similar to Message in PHP
119 function Message( map
, key
, parameters
) {
120 this.format
= 'parse';
123 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
127 * Appends parameters for replacement
129 * @param {mixed} args First in a list of variadic arguments to append as message parameters
131 Message
.prototype.params = function( parameters
) {
132 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
133 this.parameters
[this.parameters
.length
] = parameters
[i
];
139 * Converts message object to it's string form based on the state of format
141 * @return {string} String form of message
143 Message
.prototype.toString = function() {
144 if ( !this.map
.exists( this.key
) ) {
145 // Return <key> if key does not exist
146 return '<' + key
+ '>';
148 var text
= this.map
.get( this.key
);
149 var parameters
= this.parameters
;
150 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
151 var index
= parseInt( match
, 10 ) - 1;
152 return index
in parameters
? parameters
[index
] : '$' + match
;
154 /* This should be fixed up when we have a parser
155 if ( this.format === 'parse' && 'language' in mediaWiki ) {
156 text = mediaWiki.language.parse( text );
163 * Changes format to parse and converts message to string
165 * @return {string} String form of parsed message
167 Message
.prototype.parse = function() {
168 this.format
= 'parse';
169 return this.toString();
173 * Changes format to plain and converts message to string
175 * @return {string} String form of plain message
177 Message
.prototype.plain = function() {
178 this.format
= 'plain';
179 return this.toString();
183 * Checks if message exists
185 * @return {string} String form of parsed message
187 Message
.prototype.exists = function() {
188 return this.map
.exists( this.key
);
195 this.options
= new Map();
201 * Dummy function which in debug mode can be replaced with a function that does something clever
203 this.log = function() { };
206 * List of configuration values
208 * In legacy mode the values this object wraps will be in the global space
210 this.config
= new Map( LEGACY_GLOBALS
);
213 * Information about the current user
215 this.user
= new User();
218 * Localization system
220 this.messages
= new Map();
225 * Gets a message object, similar to wfMessage()
227 * @param {string} key Key of message to get
228 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $ replacement
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 * Client-side module loader which integrates with the MediaWiki ResourceLoader
244 this.loader
= new ( function() {
246 /* Private Members */
250 * Mapping of registered modules
252 * The jquery module is pre-registered, because it must have already been provided for this object to have
253 * been built, and in debug mode jquery would have been provided through a unique loader request, making it
254 * impossible to hold back registration of jquery until after mediawiki.
259 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
260 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
261 * 'script': function() {},
262 * 'style': 'css code string',
263 * 'messages': { 'key': 'value' },
264 * 'version': ############## (unix timestamp)
269 // List of modules which will be loaded as when ready
271 // List of modules to be loaded
273 // List of callback functions waiting for modules to be ready to be called
275 // Flag indicating that requests should be suspended
276 var suspended
= true;
277 // Flag inidicating that document ready has occured
280 /* Private Methods */
282 function compare( a
, b
) {
283 if ( a
.length
!= b
.length
) {
286 for ( var i
= 0; i
< b
.length
; i
++ ) {
287 if ( $.isArray( a
[i
] ) ) {
288 if ( !compare( a
[i
], b
[i
] ) ) {
292 if ( a
[i
] !== b
[i
] ) {
300 * Generates an ISO8601 "basic" string from a UNIX timestamp
302 function formatVersionNumber( timestamp
) {
303 function pad( a
, b
, c
) {
304 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
307 d
.setTime( timestamp
* 1000 );
309 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
310 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
315 * Recursively resolves dependencies and detects circular references
317 function recurse( module
, resolved
, unresolved
) {
318 if ( typeof registry
[module
] === 'undefined' ) {
319 throw new Error( 'Unknown dependency: ' + module
);
321 // Resolves dynamic loader function and replaces it with it's own results
322 if ( typeof registry
[module
].dependencies
=== 'function' ) {
323 registry
[module
].dependencies
= registry
[module
].dependencies();
324 // Ensures the module's dependencies are always in an array
325 if ( typeof registry
[module
].dependencies
!== 'object' ) {
326 registry
[module
].dependencies
= [registry
[module
].dependencies
];
329 // Tracks down dependencies
330 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
331 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
332 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
334 'Circular reference detected: ' + module
+ ' -> ' + registry
[module
].dependencies
[n
]
337 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
340 resolved
[resolved
.length
] = module
;
341 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
345 * Gets a list of modules names that a module dependencies in their proper dependency order
347 * @param mixed string module name or array of string module names
348 * @return list of dependencies
349 * @throws Error if circular reference is detected
351 function resolve( module
, resolved
, unresolved
) {
352 // Allow calling with an array of module names
353 if ( typeof module
=== 'object' ) {
355 for ( var m
= 0; m
< module
.length
; m
++ ) {
356 var dependencies
= resolve( module
[m
] );
357 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
358 modules
[modules
.length
] = dependencies
[n
];
362 } else if ( typeof module
=== 'string' ) {
363 // Undefined modules have no dependencies
364 if ( !( module
in registry
) ) {
368 recurse( module
, resolved
, [] );
371 throw new Error( 'Invalid module argument: ' + module
);
375 * Narrows a list of module names down to those matching a specific state. Possible states are 'undefined',
376 * 'registered', 'loading', 'loaded', or 'ready'
378 * @param mixed string or array of strings of module states to filter by
379 * @param array list of module names to filter (optional, all modules will be used by default)
380 * @return array list of filtered module names
382 function filter( states
, modules
) {
383 // Allow states to be given as a string
384 if ( typeof states
=== 'string' ) {
387 // If called without a list of modules, build and use a list of all modules
389 if ( typeof modules
=== 'undefined' ) {
391 for ( module
in registry
) {
392 modules
[modules
.length
] = module
;
395 // Build a list of modules which are in one of the specified states
396 for ( var s
= 0; s
< states
.length
; s
++ ) {
397 for ( var m
= 0; m
< modules
.length
; m
++ ) {
399 ( states
[s
] == 'undefined' && typeof registry
[modules
[m
]] === 'undefined' ) ||
400 ( typeof registry
[modules
[m
]] === 'object' && registry
[modules
[m
]].state
=== states
[s
] )
402 list
[list
.length
] = modules
[m
];
410 * Executes a loaded module, making it ready to use
412 * @param string module name to execute
414 function execute( module
) {
415 if ( typeof registry
[module
] === 'undefined' ) {
416 throw new Error( 'Module has not been registered yet: ' + module
);
417 } else if ( registry
[module
].state
=== 'registered' ) {
418 throw new Error( 'Module has not been requested from the server yet: ' + module
);
419 } else if ( registry
[module
].state
=== 'loading' ) {
420 throw new Error( 'Module has not completed loading yet: ' + module
);
421 } else if ( registry
[module
].state
=== 'ready' ) {
422 throw new Error( 'Module has already been loaded: ' + module
);
424 // Add style sheet to document
425 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
426 $( 'head' ).append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
427 } else if ( typeof registry
[module
].style
=== 'object' && !( registry
[module
].style
instanceof Array
) ) {
428 for ( var media
in registry
[module
].style
) {
430 '<style type="text/css" media="' + media
+ '">' + registry
[module
].style
[media
] + '</style>'
434 // Add localizations to message system
435 if ( typeof registry
[module
].messages
=== 'object' ) {
436 mediaWiki
.messages
.set( registry
[module
].messages
);
440 registry
[module
].script();
441 registry
[module
].state
= 'ready';
442 // Run jobs who's dependencies have just been met
443 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
444 if ( compare( filter( 'ready', jobs
[j
].dependencies
), jobs
[j
].dependencies
) ) {
445 if ( typeof jobs
[j
].ready
=== 'function' ) {
452 // Execute modules who's dependencies have just been met
453 for ( r
in registry
) {
454 if ( registry
[r
].state
== 'loaded' ) {
455 if ( compare( filter( ['ready'], registry
[r
].dependencies
), registry
[r
].dependencies
) ) {
461 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
463 registry
[module
].state
= 'error';
464 // Run error callbacks of jobs affected by this condition
465 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
466 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
467 if ( typeof jobs
[j
].error
=== 'function' ) {
478 * Adds a dependencies to the queue with optional callbacks to be run when the dependencies are ready or fail
480 * @param mixed string moulde name or array of string module names
481 * @param function ready callback to execute when all dependencies are ready
482 * @param function error callback to execute when any dependency fails
484 function request( dependencies
, ready
, error
) {
485 // Allow calling by single module name
486 if ( typeof dependencies
=== 'string' ) {
487 dependencies
= [dependencies
];
488 if ( dependencies
[0] in registry
) {
489 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
490 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
494 // Add ready and error callbacks if they were given
495 if ( arguments
.length
> 1 ) {
496 jobs
[jobs
.length
] = {
497 'dependencies': filter( ['undefined', 'registered', 'loading', 'loaded'], dependencies
),
502 // Queue up any dependencies that are undefined or registered
503 dependencies
= filter( ['undefined', 'registered'], dependencies
);
504 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
505 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
506 queue
[queue
.length
] = dependencies
[n
];
513 function sortQuery(o
) {
514 var sorted
= {}, key
, a
= [];
516 if ( o
.hasOwnProperty( key
) ) {
521 for ( key
= 0; key
< a
.length
; key
++ ) {
522 sorted
[a
[key
]] = o
[a
[key
]];
530 * Requests dependencies from server, loading and executing when things when ready.
532 this.work = function() {
533 // Appends a list of modules to the batch
534 for ( var q
= 0; q
< queue
.length
; q
++ ) {
535 // Only request modules which are undefined or registered
536 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
537 // Prevent duplicate entries
538 if ( $.inArray( queue
[q
], batch
) === -1 ) {
539 batch
[batch
.length
] = queue
[q
];
540 // Mark registered modules as loading
541 if ( queue
[q
] in registry
) {
542 registry
[queue
[q
]].state
= 'loading';
547 // Clean up the queue
549 // After document ready, handle the batch
550 if ( !suspended
&& batch
.length
) {
551 // Always order modules alphabetically to help reduce cache misses for otherwise identical content
553 // Build a list of request parameters
555 'skin': mediaWiki
.config
.get( 'skin' ),
556 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
557 'debug': mediaWiki
.config
.get( 'debug' )
559 // Extend request parameters with a list of modules in the batch
563 for ( var b
= 0; b
< batch
.length
; b
++ ) {
564 var group
= registry
[batch
[b
]].group
;
565 if ( !( group
in groups
) ) {
568 groups
[group
][groups
[group
].length
] = batch
[b
];
570 for ( var group
in groups
) {
571 // Calculate the highest timestamp
573 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
574 if ( registry
[groups
[group
][g
]].version
> version
) {
575 version
= registry
[groups
[group
][g
]].version
;
578 requests
[requests
.length
] = $.extend(
579 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
582 // Clear the batch - this MUST happen before we append the script element to the body or it's
583 // possible that the script will be locally cached, instantly load, and work the batch again,
584 // all before we've cleared it causing each request to include modules which are already loaded
586 // Asynchronously append a script tag to the end of the body
589 for ( var r
= 0; r
< requests
.length
; r
++ ) {
590 requests
[r
] = sortQuery( requests
[r
] );
591 // Build out the HTML
592 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
593 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
597 // Load asynchronously after doumument ready
599 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
601 document
.write( request() );
607 * Registers a module, letting the system know about it and it's dependencies. loader.js files contain calls
610 this.register = function( module
, version
, dependencies
, group
) {
611 // Allow multiple registration
612 if ( typeof module
=== 'object' ) {
613 for ( var m
= 0; m
< module
.length
; m
++ ) {
614 if ( typeof module
[m
] === 'string' ) {
615 that
.register( module
[m
] );
616 } else if ( typeof module
[m
] === 'object' ) {
617 that
.register
.apply( that
, module
[m
] );
623 if ( typeof module
!== 'string' ) {
624 throw new Error( 'module must be a string, not a ' + typeof module
);
626 if ( typeof registry
[module
] !== 'undefined' ) {
627 throw new Error( 'module already implemeneted: ' + module
);
629 // List the module as registered
631 'state': 'registered',
632 'group': typeof group
=== 'string' ? group
: null,
634 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
636 if ( typeof dependencies
=== 'string' ) {
637 // Allow dependencies to be given as a single module name
638 registry
[module
].dependencies
= [dependencies
];
639 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
640 // Allow dependencies to be given as an array of module names or a function which returns an array
641 registry
[module
].dependencies
= dependencies
;
646 * Implements a module, giving the system a course of action to take upon loading. Results of a request for
647 * one or more modules contain calls to this function.
649 this.implement = function( module
, script
, style
, localization
) {
650 // Automaically register module
651 if ( typeof registry
[module
] === 'undefined' ) {
652 that
.register( module
);
655 if ( typeof script
!== 'function' ) {
656 throw new Error( 'script must be a function, not a ' + typeof script
);
658 if ( typeof style
!== 'undefined' && typeof style
!== 'string' && typeof style
!== 'object' ) {
659 throw new Error( 'style must be a string or object, not a ' + typeof style
);
661 if ( typeof localization
!== 'undefined' && typeof localization
!== 'object' ) {
662 throw new Error( 'localization must be an object, not a ' + typeof localization
);
664 if ( typeof registry
[module
] !== 'undefined' && typeof registry
[module
].script
!== 'undefined' ) {
665 throw new Error( 'module already implemeneted: ' + module
);
667 // Mark module as loaded
668 registry
[module
].state
= 'loaded';
670 registry
[module
].script
= script
;
671 if ( typeof style
=== 'string' || typeof style
=== 'object' && !( style
instanceof Array
) ) {
672 registry
[module
].style
= style
;
674 if ( typeof localization
=== 'object' ) {
675 registry
[module
].messages
= localization
;
677 // Execute or queue callback
678 if ( compare( filter( ['ready'], registry
[module
].dependencies
), registry
[module
].dependencies
) ) {
686 * Executes a function as soon as one or more required modules are ready
688 * @param mixed string or array of strings of modules names the callback dependencies to be ready before
690 * @param function callback to execute when all dependencies are ready (optional)
691 * @param function callback to execute when if dependencies have a errors (optional)
693 this.using = function( dependencies
, ready
, error
) {
695 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
696 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
698 // Allow calling with a single dependency as a string
699 if ( typeof dependencies
=== 'string' ) {
700 dependencies
= [dependencies
];
702 // Resolve entire dependency map
703 dependencies
= resolve( dependencies
);
704 // If all dependencies are met, execute ready immediately
705 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
706 if ( typeof ready
=== 'function' ) {
710 // If any dependencies have errors execute error immediately
711 else if ( filter( ['error'], dependencies
).length
) {
712 if ( typeof error
=== 'function' ) {
716 // Since some dependencies are not yet ready, queue up a request
718 request( dependencies
, ready
, error
);
723 * Loads an external script or one or more modules for future use
725 * @param {mixed} modules either the name of a module, array of modules, or a URL of an external script or style
726 * @param {string} type mime-type to use if calling with a URL of an external script or style; acceptable values
727 * are "text/css" and "text/javascript"; if no type is provided, text/javascript is assumed
729 this.load = function( modules
, type
) {
731 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
732 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
734 // Allow calling with an external script or single dependency as a string
735 if ( typeof modules
=== 'string' ) {
736 // Support adding arbitrary external scripts
737 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
738 if ( type
=== 'text/css' ) {
739 $( 'head' ).append( $( '<link rel="stylesheet" type="text/css" />' ).attr( 'href', modules
) );
741 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
742 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
744 $( 'body' ).append( script
);
746 document
.write( script
);
753 // Called with single module
756 // Resolve entire dependency map
757 modules
= resolve( modules
);
758 // If all modules are ready, nothing dependency be done
759 if ( compare( filter( ['ready'], modules
), modules
) ) {
762 // If any modules have errors return false
763 else if ( filter( ['error'], modules
).length
) {
766 // Since some modules are not yet ready, queue up a request
774 * Flushes the request queue and begin executing load requests on demand
776 this.go = function() {
782 * Changes the state of a module
784 * @param mixed module string module name or object of module name/state pairs
785 * @param string state string state name
787 this.state = function( module
, state
) {
788 if ( typeof module
=== 'object' ) {
789 for ( var m
in module
) {
790 that
.state( m
, module
[m
] );
794 if ( !( module
in registry
) ) {
795 that
.register( module
);
797 registry
[module
].state
= state
;
801 * Gets the version of a module
803 * @param string module name of module to get version for
805 this.version = function( module
) {
806 if ( module
in registry
&& 'version' in registry
[module
] ) {
807 return formatVersionNumber( registry
[module
].version
);
812 /* Cache document ready status */
814 $(document
).ready( function() { ready
= true; } );
817 /* Extension points */
823 /* Auto-register from pre-loaded startup scripts */
825 if ( typeof startUp
=== 'function' ) {
830 // Alias $j to jQuery for backwards compatibility
832 window
.mw
= mediaWiki
;