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*$/, "");
25 // Add array comparison functionality
26 if (typeof Array
.prototype.compare
=== 'undefined') {
27 Array
.prototype.compare = function (against
) {
28 if (this.length
!== against
.length
) {
31 for (var i
= 0; i
< against
.length
; i
++) {
32 if (this[i
].compare
) {
33 if (!this[i
].compare(against
[i
])) {
37 if (this[i
] !== against
[i
]) {
45 // Make calling .indexOf() on an array work on older browsers
46 if (typeof Array
.prototype.indexOf
=== 'undefined') {
47 Array
.prototype.indexOf = function (needle
) {
48 for (var i
= 0; i
< this.length
; i
++) {
49 if (this[i
] === needle
) {
58 * Core MediaWiki JavaScript Library
61 window
.mediaWiki
= new ( function( $ ) {
65 // This will not change until we are 100% ready to turn off legacy globals
66 var LEGACY_GLOBALS
= true;
76 * An object which allows single and multiple get/set/exists functionality on a list of key / value pairs
78 * @param {boolean} global whether to get/set/exists values on the window object or a private object
79 * @param {function} parser function to perform extra processing; in the form of function( value, options )
80 * @param {function} fallback function to format default fallback; in the form of function( key )
81 * where value is the data to be parsed and options is additional data passed through to the parser
83 'map': function( global
, parser
, fallback
) {
88 var values
= global
=== true ? window
: {};
93 * Gets one or more values
95 * If called with no arguments, all values will be returned. If a parser is in use, no parsing will take
96 * place when calling with no arguments or calling with an array of names.
98 * @param {mixed} selection string name of value to get, array of string names of values to get, or object
99 * of name/option pairs
100 * @param {object} options optional set of options which are also passed to a parser if in use; only used
101 * when selection is a string
104 * // Value to use if key does not exist
108 this.get = function( selection
, options
) {
109 if ( typeof selection
=== 'object' ) {
111 for ( var s
in selection
) {
112 if ( selection
.hasOwnProperty( s
) ) {
113 if ( typeof s
=== 'string' ) {
114 return that
.get( values
[s
], selection
[s
] );
116 return that
.get( selection
[s
] );
121 } else if ( typeof selection
=== 'string' ) {
122 if ( typeof values
[selection
] === 'undefined' ) {
123 if ( typeof options
=== 'object' && 'fallback' in options
) {
124 return options
.fallback
;
125 } else if ( typeof fallback
=== 'function' ) {
126 return fallback( selection
);
131 if ( typeof parser
=== 'function' ) {
132 return parser( values
[selection
], options
);
134 return values
[selection
];
143 * Sets one or multiple configuration values using a key and a value or an object of keys and values
145 * @param {mixed} key string of name by which value will be made accessible, or object of name/value pairs
146 * @param {mixed} value optional value to set, only in use when key is a string
148 this.set = function( selection
, value
) {
149 if ( typeof selection
=== 'object' ) {
150 for ( var s
in selection
) {
151 values
[s
] = selection
[s
];
153 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
154 values
[selection
] = value
;
159 * Checks if one or multiple configuration fields exist
161 this.exists = function( selection
) {
162 if ( typeof keys
=== 'object' ) {
163 for ( var s
= 0; s
< selection
.length
; s
++ ) {
164 if ( !( selection
[s
] in values
) ) {
170 return selection
in values
;
179 * Dummy function which in debug mode can be replaced with a function that does something clever
181 this.log = function() { };
184 * List of configuration values
186 * In legacy mode the values this object wraps will be in the global space
188 this.config
= new this.prototypes
.map( LEGACY_GLOBALS
);
191 * Information about the current user
193 this.user
= new ( function() {
197 this.options
= new that
.prototypes
.map();
201 * Basic parser, can be replaced with something more robust
203 this.parser = function( text
, options
) {
204 if ( typeof options
=== 'object' && typeof options
.parameters
=== 'object' ) {
205 text
= text
.replace( /\$(\d+)/g, function( str
, match
) {
206 var index
= parseInt( match
, 10 ) - 1;
207 return index
in options
.parameters
? options
.parameters
[index
] : '$' + match
;
214 * Localization system
216 this.msg
= new that
.prototypes
.map( false, this.parser
, function( key
) { return '<' + key
+ '>'; } );
219 * Client-side module loader which integrates with the MediaWiki ResourceLoader
221 this.loader
= new ( function() {
223 /* Private Members */
227 * Mapping of registered modules
229 * The jquery module is pre-registered, because it must have already been provided for this object to have
230 * been built, and in debug mode jquery would have been provided through a unique loader request, making it
231 * impossible to hold back registration of jquery until after mediawiki.
236 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
237 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
238 * 'script': function() {},
239 * 'style': 'css code string',
240 * 'messages': { 'key': 'value' },
241 * 'version': ############## (unix timestamp)
246 // List of modules which will be loaded as when ready
248 // List of modules to be loaded
250 // List of callback functions waiting for modules to be ready to be called
252 // Flag indicating that requests should be suspended
253 var suspended
= true;
254 // Flag inidicating that document ready has occured
257 /* Private Methods */
260 * Generates an ISO8601 "basic" string from a UNIX timestamp
262 function formatVersionNumber( timestamp
) {
263 function pad( a
, b
, c
) {
264 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
267 d
.setTime( timestamp
* 1000 );
269 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
270 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
275 * Recursively resolves dependencies and detects circular references
277 function recurse( module
, resolved
, unresolved
) {
278 unresolved
[unresolved
.length
] = module
;
279 // Resolves dynamic loader function and replaces it with it's own results
280 if ( typeof registry
[module
].dependencies
=== 'function' ) {
281 registry
[module
].dependencies
= registry
[module
].dependencies();
282 // Ensures the module's dependencies are always in an array
283 if ( typeof registry
[module
].dependencies
!== 'object' ) {
284 registry
[module
].dependencies
= [registry
[module
].dependencies
];
287 // Tracks down dependencies
288 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
289 if ( resolved
.indexOf( registry
[module
].dependencies
[n
] ) === -1 ) {
290 if ( unresolved
.indexOf( registry
[module
].dependencies
[n
] ) !== -1 ) {
292 'Circular reference detected: ' + module
+ ' -> ' + registry
[module
].dependencies
[n
]
295 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
298 resolved
[resolved
.length
] = module
;
299 unresolved
.splice( unresolved
.indexOf( module
), 1 );
303 * Gets a list of modules names that a module dependencies in their proper dependency order
305 * @param mixed string module name or array of string module names
306 * @return list of dependencies
307 * @throws Error if circular reference is detected
309 function resolve( module
, resolved
, unresolved
) {
310 // Allow calling with an array of module names
311 if ( typeof module
=== 'object' ) {
313 for ( var m
= 0; m
< module
.length
; m
++ ) {
314 var dependencies
= resolve( module
[m
] );
315 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
316 modules
[modules
.length
] = dependencies
[n
];
320 } else if ( typeof module
=== 'string' ) {
321 // Undefined modules have no dependencies
322 if ( !( module
in registry
) ) {
326 recurse( module
, resolved
, [] );
329 throw new Error( 'Invalid module argument: ' + module
);
333 * Narrows a list of module names down to those matching a specific state. Possible states are 'undefined',
334 * 'registered', 'loading', 'loaded', or 'ready'
336 * @param mixed string or array of strings of module states to filter by
337 * @param array list of module names to filter (optional, all modules will be used by default)
338 * @return array list of filtered module names
340 function filter( states
, modules
) {
341 // Allow states to be given as a string
342 if ( typeof states
=== 'string' ) {
345 // If called without a list of modules, build and use a list of all modules
347 if ( typeof modules
=== 'undefined' ) {
349 for ( module
in registry
) {
350 modules
[modules
.length
] = module
;
353 // Build a list of modules which are in one of the specified states
354 for ( var s
= 0; s
< states
.length
; s
++ ) {
355 for ( var m
= 0; m
< modules
.length
; m
++ ) {
357 ( states
[s
] == 'undefined' && typeof registry
[modules
[m
]] === 'undefined' ) ||
358 ( typeof registry
[modules
[m
]] === 'object' && registry
[modules
[m
]].state
=== states
[s
] )
360 list
[list
.length
] = modules
[m
];
368 * Executes a loaded module, making it ready to use
370 * @param string module name to execute
372 function execute( module
) {
373 if ( typeof registry
[module
] === 'undefined' ) {
374 throw new Error( 'Module has not been registered yet: ' + module
);
375 } else if ( registry
[module
].state
=== 'registered' ) {
376 throw new Error( 'Module has not been requested from the server yet: ' + module
);
377 } else if ( registry
[module
].state
=== 'loading' ) {
378 throw new Error( 'Module has not completed loading yet: ' + module
);
379 } else if ( registry
[module
].state
=== 'ready' ) {
380 throw new Error( 'Module has already been loaded: ' + module
);
382 // Add style sheet to document
383 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
384 $( 'head' ).append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
385 } else if ( typeof registry
[module
].style
=== 'object' && !( registry
[module
].style
instanceof Array
) ) {
386 for ( var media
in registry
[module
].style
) {
388 '<style type="text/css" media="' + media
+ '">' + registry
[module
].style
[media
] + '</style>'
392 // Add localizations to message system
393 if ( typeof registry
[module
].messages
=== 'object' ) {
394 mediaWiki
.msg
.set( registry
[module
].messages
);
398 registry
[module
].script();
399 registry
[module
].state
= 'ready';
400 // Run jobs who's dependencies have just been met
401 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
402 if ( filter( 'ready', jobs
[j
].dependencies
).compare( jobs
[j
].dependencies
) ) {
403 if ( typeof jobs
[j
].ready
=== 'function' ) {
410 // Execute modules who's dependencies have just been met
411 for ( r
in registry
) {
412 if ( registry
[r
].state
== 'loaded' ) {
413 if ( filter( ['ready'], registry
[r
].dependencies
).compare( registry
[r
].dependencies
) ) {
419 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
421 registry
[module
].state
= 'error';
422 // Run error callbacks of jobs affected by this condition
423 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
424 if ( jobs
[j
].dependencies
.indexOf( module
) !== -1 ) {
425 if ( typeof jobs
[j
].error
=== 'function' ) {
436 * Adds a dependencies to the queue with optional callbacks to be run when the dependencies are ready or fail
438 * @param mixed string moulde name or array of string module names
439 * @param function ready callback to execute when all dependencies are ready
440 * @param function error callback to execute when any dependency fails
442 function request( dependencies
, ready
, error
) {
443 // Allow calling by single module name
444 if ( typeof dependencies
=== 'string' ) {
445 dependencies
= [dependencies
];
446 if ( dependencies
[0] in registry
) {
447 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
448 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
452 // Add ready and error callbacks if they were given
453 if ( arguments
.length
> 1 ) {
454 jobs
[jobs
.length
] = {
455 'dependencies': filter( ['undefined', 'registered', 'loading', 'loaded'], dependencies
),
460 // Queue up any dependencies that are undefined or registered
461 dependencies
= filter( ['undefined', 'registered'], dependencies
);
462 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
463 if ( queue
.indexOf( dependencies
[n
] ) === -1 ) {
464 queue
[queue
.length
] = dependencies
[n
];
471 function sortQuery(o
) {
472 var sorted
= {}, key
, a
= [];
474 if ( o
.hasOwnProperty( key
) ) {
479 for ( key
= 0; key
< a
.length
; key
++ ) {
480 sorted
[a
[key
]] = o
[a
[key
]];
488 * Requests dependencies from server, loading and executing when things when ready.
490 this.work = function() {
491 // Appends a list of modules to the batch
492 for ( var q
= 0; q
< queue
.length
; q
++ ) {
493 // Only request modules which are undefined or registered
494 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
495 // Prevent duplicate entries
496 if ( batch
.indexOf( queue
[q
] ) === -1 ) {
497 batch
[batch
.length
] = queue
[q
];
498 // Mark registered modules as loading
499 if ( queue
[q
] in registry
) {
500 registry
[queue
[q
]].state
= 'loading';
505 // Clean up the queue
507 // After document ready, handle the batch
508 if ( !suspended
&& batch
.length
) {
509 // Always order modules alphabetically to help reduce cache misses for otherwise identical content
511 // Build a list of request parameters
513 'skin': mediaWiki
.config
.get( 'skin' ),
514 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
515 'debug': mediaWiki
.config
.get( 'debug' )
517 // Extend request parameters with a list of modules in the batch
521 for ( var b
= 0; b
< batch
.length
; b
++ ) {
522 var group
= registry
[batch
[b
]].group
;
523 if ( !( group
in groups
) ) {
526 groups
[group
][groups
[group
].length
] = batch
[b
];
528 for ( var group
in groups
) {
529 // Calculate the highest timestamp
531 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
532 if ( registry
[groups
[group
][g
]].version
> version
) {
533 version
= registry
[groups
[group
][g
]].version
;
536 requests
[requests
.length
] = $.extend(
537 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
540 // Clear the batch - this MUST happen before we append the script element to the body or it's
541 // possible that the script will be locally cached, instantly load, and work the batch again,
542 // all before we've cleared it causing each request to include modules which are already loaded
544 // Asynchronously append a script tag to the end of the body
547 for ( var r
= 0; r
< requests
.length
; r
++ ) {
548 requests
[r
] = sortQuery( requests
[r
] );
549 // Build out the HTML
550 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
551 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
555 // Load asynchronously after doumument ready
557 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
559 document
.write( request() );
565 * Registers a module, letting the system know about it and it's dependencies. loader.js files contain calls
568 this.register = function( module
, version
, dependencies
, group
) {
569 // Allow multiple registration
570 if ( typeof module
=== 'object' ) {
571 for ( var m
= 0; m
< module
.length
; m
++ ) {
572 if ( typeof module
[m
] === 'string' ) {
573 that
.register( module
[m
] );
574 } else if ( typeof module
[m
] === 'object' ) {
575 that
.register
.apply( that
, module
[m
] );
581 if ( typeof module
!== 'string' ) {
582 throw new Error( 'module must be a string, not a ' + typeof module
);
584 if ( typeof registry
[module
] !== 'undefined' ) {
585 throw new Error( 'module already implemeneted: ' + module
);
587 // List the module as registered
589 'state': 'registered',
590 'group': typeof group
=== 'string' ? group
: null,
592 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
594 if ( typeof dependencies
=== 'string' ) {
595 // Allow dependencies to be given as a single module name
596 registry
[module
].dependencies
= [dependencies
];
597 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
598 // Allow dependencies to be given as an array of module names or a function which returns an array
599 registry
[module
].dependencies
= dependencies
;
604 * Implements a module, giving the system a course of action to take upon loading. Results of a request for
605 * one or more modules contain calls to this function.
607 this.implement = function( module
, script
, style
, localization
) {
608 // Automaically register module
609 if ( typeof registry
[module
] === 'undefined' ) {
610 that
.register( module
);
613 if ( typeof script
!== 'function' ) {
614 throw new Error( 'script must be a function, not a ' + typeof script
);
616 if ( typeof style
!== 'undefined' && typeof style
!== 'string' && typeof style
!== 'object' ) {
617 throw new Error( 'style must be a string or object, not a ' + typeof style
);
619 if ( typeof localization
!== 'undefined' && typeof localization
!== 'object' ) {
620 throw new Error( 'localization must be an object, not a ' + typeof localization
);
622 if ( typeof registry
[module
] !== 'undefined' && typeof registry
[module
].script
!== 'undefined' ) {
623 throw new Error( 'module already implemeneted: ' + module
);
625 // Mark module as loaded
626 registry
[module
].state
= 'loaded';
628 registry
[module
].script
= script
;
629 if ( typeof style
=== 'string' || typeof style
=== 'object' && !( style
instanceof Array
) ) {
630 registry
[module
].style
= style
;
632 if ( typeof localization
=== 'object' ) {
633 registry
[module
].messages
= localization
;
635 // Execute or queue callback
636 if ( filter( ['ready'], registry
[module
].dependencies
).compare( registry
[module
].dependencies
) ) {
644 * Executes a function as soon as one or more required modules are ready
646 * @param mixed string or array of strings of modules names the callback dependencies to be ready before
648 * @param function callback to execute when all dependencies are ready (optional)
649 * @param function callback to execute when if dependencies have a errors (optional)
651 this.using = function( dependencies
, ready
, error
) {
653 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
654 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
656 // Allow calling with a single dependency as a string
657 if ( typeof dependencies
=== 'string' ) {
658 dependencies
= [dependencies
];
660 // Resolve entire dependency map
661 dependencies
= resolve( dependencies
);
662 // If all dependencies are met, execute ready immediately
663 if ( filter( ['ready'], dependencies
).compare( dependencies
) ) {
664 if ( typeof ready
=== 'function' ) {
668 // If any dependencies have errors execute error immediately
669 else if ( filter( ['error'], dependencies
).length
) {
670 if ( typeof error
=== 'function' ) {
674 // Since some dependencies are not yet ready, queue up a request
676 request( dependencies
, ready
, error
);
681 * Loads an external script or one or more modules for future use
683 * @param {mixed} modules either the name of a module, array of modules, or a URL of an external script or style
684 * @param {string} type mime-type to use if calling with a URL of an external script or style; acceptable values
685 * are "text/css" and "text/javascript"; if no type is provided, text/javascript is assumed
687 this.load = function( modules
, type
) {
689 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
690 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
692 // Allow calling with an external script or single dependency as a string
693 if ( typeof modules
=== 'string' ) {
694 // Support adding arbitrary external scripts
695 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
696 if ( type
=== 'text/css' ) {
697 $( 'head' ).append( $( '<link rel="stylesheet" type="text/css" />' ).attr( 'href', modules
) );
699 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
700 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
702 $( 'body' ).append( script
);
704 document
.write( script
);
711 // Called with single module
714 // Resolve entire dependency map
715 modules
= resolve( modules
);
716 // If all modules are ready, nothing dependency be done
717 if ( filter( ['ready'], modules
).compare( modules
) ) {
720 // If any modules have errors return false
721 else if ( filter( ['error'], modules
).length
) {
724 // Since some modules are not yet ready, queue up a request
732 * Flushes the request queue and begin executing load requests on demand
734 this.go = function() {
740 * Changes the state of a module
742 * @param mixed module string module name or object of module name/state pairs
743 * @param string state string state name
745 this.state = function( module
, state
) {
746 if ( typeof module
=== 'object' ) {
747 for ( var m
in module
) {
748 that
.state( m
, module
[m
] );
752 if ( !( module
in registry
) ) {
753 that
.register( module
);
755 registry
[module
].state
= state
;
759 * Gets the version of a module
761 * @param string module name of module to get version for
763 this.version = function( module
) {
764 if ( module
in registry
&& 'version' in registry
[module
] ) {
765 return formatVersionNumber( registry
[module
].version
);
770 /* Cache document ready status */
772 $(document
).ready( function() { ready
= true; } );
775 /* Extension points */
781 /* Auto-register from pre-loaded startup scripts */
783 if ( typeof startUp
=== 'function' ) {
788 // Alias $j to jQuery for backwards compatibility
790 window
.mw
= mediaWiki
;